HTML5 Game - Canvas Animation Sprite

Moving the Image Across the Canvas to do Sprite animation and movement

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { //from  w w w  .ja v a  2 s  .  co m
  border:1px solid #03F; 
  background:#CFC; 
} 
</style> 
</head> 
<body> 
<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 dx=0;
  let dy=-1;
  let x=50;
  let y=50;
  
  function eventSheetLoaded() {
    startUp();
  }

  function drawScreen() {
     
     y=y+dy;
     x=x+dx;
     
     
    //draw a background so we can wee the Canvas edges
    context.fillStyle="#aaaaaa";
    context.fillRect(0,0,500,500);
    
    let sourceX=Math.floor(animationFrames[frameIndex] % 8) *32;
    let sourceY=Math.floor(animationFrames[frameIndex] / 8) *32;
     
    context.drawImage(tileSheet, sourceX, sourceY,32,32,x,y,32,32);
         
    frameIndex++;
    if (frameIndex ==animationFrames.length) {
       frameIndex=0;
    }
     
  }
  
  function startUp(){
    gameLoop();
  }
   
  function gameLoop() {
    window.setTimeout(gameLoop, 100);
    drawScreen();    
  }

</script> 



</body> 
</html>

Related Topics