HTML5 Game - Applying Rotation Transformations to an Image

Description

Applying Rotation Transformations to an Image

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { //from  w w  w .  ja  va 2 s.c  o m
  border:1px solid #03F; 
  background:#CFC; 
} 
</style> 
</head> 
<body> 
<p>Here is the sprite image:</p>
<img src='http://java2s.com/style/demo/tank1.png'/>
<canvas id="canvas" width="640" height="480"></canvas> 
<script> 

  let context = document.getElementById('canvas').getContext('2d'); 


  let tileSheet=new Image();
  tileSheet.addEventListener('load', eventSheetLoaded , false);
  tileSheet.src="http://java2s.com/style/demo/tank1.png";
  
  
  let animationFrames=[1,2,3,4,5,6,7];
  let frameIndex=0;
  let rotation=90;
  
  let x=50;
  let y=50;
  
  function eventSheetLoaded() {
    drawScreen();
  }

  function drawScreen() {
  
     
    //draw a background so we can wee the Canvas edges
    context.fillStyle="#aaaaaa";
    context.fillRect(0,0,500,500);
    
    context.save();
    context.setTransform(1,0,0,1,0,0)
    
    context.translate(x+16, y+16);
    let angleInRadians =rotation * Math.PI / 180;
    context.rotate(angleInRadians);
    
    let sourceX=Math.floor(animationFrames[frameIndex] % 8) *32;
    let sourceY=Math.floor(animationFrames[frameIndex] / 8) *32;
     
    context.drawImage(tileSheet, sourceX, sourceY,32,32,-16,-16,32,32);
         
    context.restore();
     
  }
  

</script> 



</body> 
</html>

Related Topic