HTML5 Game - Create moving tank using sprite images

Description

Create moving tank using sprite images

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { /*from  ww w  .  java2 s  .co  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;
  
  function eventSheetLoaded() {
    startUp();
  }

  function drawScreen() {
     
    //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,50,50,32,32);
         
    frameIndex++;
    if (frameIndex ==animationFrames.length) {
       frameIndex=0;
    }
     
  }
  
  function startUp(){
    gameLoop();
  }
   
  function gameLoop() {
    window.setTimeout(gameLoop, 100);
    drawScreen();    
  }

</script> 



</body> 
</html>

Related Topic