Changing the Tile to Display
To change the tile to display, we can multiply the counter
variable by 32
(the tile width).
Because we have only a single row of tiles, we don’t have to change the
y
value:
context
.
drawImage
(
tileSheet
,
32
*
counter
,
0
,
32
,
32
,
50
,
50
,
64
,
64
);
Note
We will examine how to use a tile sheet consisting of multiple rows and columns in the next section, Advanced Cell-Based Animation.
Example 4-3 used this same line of code to draw our image. In Example 4-4, it will be placed on the canvas at 50,50 and scaled to 64×64 pixels. Let’s look at the entire set of code.
Example 4-4. A simple sprite animation
var
counter
=
0
;
var
tileSheet
=
new
Image
();
tileSheet
.
addEventListener
(
'load'
,
eventSheetLoaded
,
false
);
tileSheet
.
src
=
"ships.png"
;
function
eventSheetLoaded
()
{
startUp
();
}
function
drawScreen
()
{
//draw a background so we can see the Canvas edges
context
.
fillStyle
=
"#aaaaaa"
;
context
.
fillRect
(
0
,
0
,
500
,
500
);
context
.
drawImage
(
tileSheet
,
32
*
counter
,
0
,
32
,
32
,
50
,
50
,
64
,
64
);
counter
++
;
if
(
counter
>
1
)
{
counter
=
0
;
}
}
function
startUp
(){
gameLoop
();
}
function
gameLoop
()
{
window
.
setTimeout
(
gameLoop
,
100
);
drawScreen
();
}
When you run this code, you will see the exhaust on the ship turn off and on every 100 milliseconds, creating a simple cell-based animation.
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.