Rendering Logic Overview
Each time the game renders objects to the screen, it runs through the entirerender()
function. It does this to ensure that even the nonmoving objects are rendered back to the game screen. Therender()
function looks like this:
function
renderPlayField
()
{
fillBackground
();
drawPlayField
();
drawPlayer
();
drawEnemy
();
drawExplosions
();
}
First, we draw the plain black background, and then we drawplayField
. After that, we draw the game objects.drawPlayField()
draws the map of tiles to the game screen. This function is similar to the functions inChapter 4 but with some additions for our game. Let’s review how it is organized:
function
drawPlayField
(){
for
(
rowCtr
=
0
;
rowCtr
<
15
;
rowCtr
++
){
for
(
colCtr
=
0
;
colCtr
<
15
;
colCtr
++
)
{
var
sourceX
=
Math
.
floor
((
playField
[
rowCtr
][
colCtr
])
%
8
)
*
32
;
var
sourceY
=
Math
.
floor
((
playField
[
rowCtr
][
colCtr
])
/
8
)
*
32
;
if
(
playField
[
rowCtr
][
colCtr
]
!=
roadTile
){
context
.
drawImage
(
tileSheet
,
0
,
0
,
32
,
32
,
colCtr
*
32
,
rowCtr
*
32
,
32
,
32
);
}
context
.
drawImage
(
tileSheet
,
sourceX
,
sourceY
,
32
,
32
,
colCtr
*
32
,
rowCtr
*
32
,
32
,
32
);
}
}
}
ThedrawPlayField()
function loops through the rows in theplayField
array and then through each column inside each row. If the tile ID number atplayField[rowCtr][colCtr]
is a road tile, it simply paints that tile at the correct location onplayField
. If the tile ID is a game object (not a road tile), it first paints a road tile in that spot and then paints the object tile in that spot.
GetHTML5 Canvas, 2nd Edition now with the O’Reillylearning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly andnearly 200 top publishers.