HTML and CSS Reference
In-Depth Information
function eventShipLoaded() {
startUp();
}
function drawScreen() {
//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,50,50,32,32);
frameIndex++;
if (frameIndex ==animationFrames.length) {
frameIndex=0;
}
}
function startUp(){
setInterval(drawScreen, 100 );
}
When we run the example, we will see the eight tile cell frames for the tank run in order
and then repeat—the only problem is that the tank isn't going anywhere. Let's solve
that little dilemma next and drive the tank up the screen.
Moving the Image Across the Canvas
Now that we have the tank tracks animating, let's “move” the tank. By animating the
tank tracks and applying a simple movement vector to the tank's position, we can
achieve the simulation of animated movement.
To do this, we first need to create variables to hold the current x and y positions of the
tank. These represent the top-left corner where the tile from our sheet will be drawn
to the canvas. In the previous examples, this number was set at 50 for each, so let's use
that value here as well:
var x = 50;
var y = 50;
We also need a movement vector value for each axis. These are commonly known as
deltaX ( dx ) and deltaY ( dy ). They represent the “delta” or “change” in the x or y axis
position on each iteration. Our tank is currently facing in the “up” position, so we will
use -1 for the dy and 0 for the dx :
var dx = 0;
var dy = -1;
Search WWH ::




Custom Search