HTML and CSS Reference
In-Depth Information
Moving the Image Across the Canvas
Now that we have the tank treads animating, let's “move” the tank. By animating the tank
treads and applying a simple movement vector to the tank's position, we can achieve the sim-
ulation 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
var
x
=
50
;
var
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
var
dx
=
0
;
var
var
dy
=
−
1
;
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. Sprite animation and movement
var
var
tileSheet
=
new
new
Image
();
tileSheet
.
addEventListener
(
'load'
,
eventSheetLoaded
,
false
false
);
tileSheet
.
src
=
"tanks_sheet.png"
;
var
var
animationFrames
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
];
var
var
frameIndex
=
0
;
var
var
dx
=
0
;