Choosing the Tile to Display
We will use the frameIndex
of the
animationFrames
array to calculate
the 32×32 source rectangle from our tile sheet that we will copy to the
canvas. First, we need to find the x
and y
locations of the top-left
corner for the tile we want to copy. To do this, we will create local
variables in our drawScreen()
function on each iteration (frame) to calculate the position on the tile
sheet. The sourceX
variable will
contain the top-left corner x
position, and the sourceY
variable
will contain the top-left corner y
position.
Here is pseudocode for the sourceX
calculation:
sourceX
=
integer
(
current_frame_index
modulo
the_number_columns_in_the_tilesheet
)
*
tile_width
The modulo (%) operator gives us the remainder of the division calculation. The actual code we will use for this calculation looks like this:
var
sourceX
=
Math
.
floor
(
animationFrames
[
frameIndex
]
%
8
)
*
32
;
The calculation for the sourceY
value is similar, except we divide rather than use the modulo
operation:
sourceY
=
integer
(
current_frame_index
divided
by
the_number_columns_in_the_tilesheet
)
*
tile_height
Here is the actual code we will use for this calculation:
var
sourceY
=
Math
.
floor
(
animationFrames
[
frameIndex
]
/
8
)
*
32
;
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.