HTML and CSS Reference
In-Depth Information
We will create a simple integer to count which frame we are displaying on our tile sheet:
var counter = 0;
Inside
drawScreen()
, we will increment this value by
1
on each frame. Since we only
have two frames, we will need to set it back to
0
when it is greater than
1
:
counter++;
if (counter >1) {
counter = 0;
}
Or use the nice shortcut:
counter ^= 1;
Creating a Timer Loop
As it currently stands, our code will only be called a single time. Let's create a simple
timer loop that will call the
drawScreen()
function 10 times a second, or once every 100
milliseconds. A timer loop that is set to run at a certain frame rate is sometimes referred
to as a
frame tick
or
timer tick
. Each tick is simply a single iteration of the timer running
all the code we put into our
drawScreen()
function. We will also need a function that
starts the timer loop and initiates the tick once the image has preloaded properly. We'll
name this function
startUp()
:
function eventShipLoaded() {
startUp();
}
function startUp(){
setInterval(drawScreen, 100 );
}
Changing the Tile to Display
To change the tile to display, we can multiply the counter variable by
32
(the tile width).
Since we only have 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);
We will examine how to use a tile sheet consisting of multiple
rows and columns in the next section,
“Advanced Cell-Based Anima-
tion” on page 132
.
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.