HTML and CSS Reference
In-Depth Information
The result is that on each frame tick, our tank will move one pixel up on the y-axis and
zero pixels on the x-axis.
Inside drawScreen() (which is called on each frame tick), we will add the dx and dy
values to the x and y values, and then apply them to the drawImage() function:
y = y+dy;
x = x+dx;
context.drawImage(tileSheet, sourceX, sourceY,32,32,x,y,32,32);
Rather than use the hardcoded 50,50 for the location of the drawImage() call on the
canvas, we have replaced it with the current x,y position. Let's examine the entire code
in Example 4-6 .
Example 4-6. Sprite animation and movement
var tileSheet = new Image();
tileSheet.addEventListener('load', eventShipLoaded , false);
tileSheet.src = "tanks_sheet.png";
var animationFrames = [1,2,3,4,5,6,7,8];
var frameIndex = 0;
var dx = 0;
var dy = -1;
var x = 50;
var y = 50;
function eventShipLoaded() {
startUp();
}
function drawScreen() {
y = y+dy;
x = x+dx;
//draw a background so we can see the Canvas edges
context.fillStyle = "#aaaaaa";
context.fillRect(0,0,500,500);
var sourceX = Math.floor(animationFrames[frameIndex] % 8) *32;
var 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(){
Search WWH ::




Custom Search