HTML and CSS Reference
In-Depth Information
Changing the Tile to Display
To change the tile to display, we can multiply the counter variable by 32 (the tile width). Be-
cause 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
var counter = 0 ;
var
var tileSheet = new
new Image ();
tileSheet . addEventListener ( 'load' , eventSheetLoaded , false
false );
tileSheet . src = "ships.png" ;
function
function eventSheetLoaded () {
startUp ();
}
function
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 ++ ;
iif ( counter > 1 ) {
counter = 0 ;
}
}
function
function startUp (){
gameLoop ();
}
function
function gameLoop () {
window . setTimeout ( gameLoop , 100 );
Search WWH ::




Custom Search