HTML5 Game - A moving tank by sprite image

Description

A moving tank by sprite image

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { //  w w w  .ja v  a 2 s  .c  om
  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;
  let dx=1;
  let dy=0;
  
  function eventSheetLoaded() {
    startUp();
  }

  function drawScreen() {
     x=x+dx;
     y=y+dy;
     
    //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)
    let angleInRadians =rotation * Math.PI / 180;
    context.translate(x+16, y+16)
    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();
         
    frameIndex++;
    if (frameIndex ==animationFrames.length) {
       frameIndex=0;
    }
     
  }
  
  function startUp(){
    gameLoop();
  }
   
  function gameLoop() {
    window.setTimeout(gameLoop, 100);
    drawScreen();    
  }



</script> 



</body> 
</html>

Related Topic