HTML and CSS Reference
In-Depth Information
Drawing the Tile
We will use
drawImage()
to place the new tile on the screen on each iteration:
context
.
drawImage
(
tileSheet
,
sourceX
,
sourceY
,
32
,
32
,
50
,
50
,
32
,
32
);
Here, we are passing the calculated
sourceX
and
sourceY
values into the
drawImage()
func-
tion. We then pass in the width (
32
), the height (
32
), and the location (
50,50
) to draw the
image on the canvas.
Example 4-5
shows the full code.
Example 4-5. Advanced sprite animation
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
;
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
);
var
var
sourceX
=
Math
.
floor
(
animationFrames
[
frameIndex
]
%
8
)
*
32
;
var
var
sourceY
=
Math
.
floor
(
animationFrames
[
frameIndex
]
/
8
)
*
32
;
context
.
drawImage
(
tileSheet
,
sourceX
,
sourceY
,
32
,
32
,
50
,
50
,
32
,
32
);
frameIndex
++
;
iif
(
frameIndex
==
animationFrames
.
length
) {
frameIndex
=
0
;
}
}
function
function
startUp
(){
gameLoop
();
}
function
function
gameLoop
() {
window
.
setTimeout
(
gameLoop
,
100
);