Using Paths to Draw the Game’s Main Character
Paths offer us a very simple but powerful way to mimic the vector look of the classic Asteroids game. We could use bitmap images for this purpose, but in this chapter we are going to focus on creating our game in code with no external assets. Let’s take a look at the two frames of animation we will create for our player ship.
The static player ship (frame 1)
The main frame of the player ship will be drawn with paths on a 20×20 grid, as shown in Figure 8-2.
Figure 8-2. The player ship
Using the basic HTML file presented in Example 8-1, we can simply swap the
drawScreen()
function with the code
in Example 8-2 to draw the ship.
Example 8-2. Drawing the player ship
function
drawScreen
()
{
// draw background and text
context
.
fillStyle
=
'#000000'
;
context
.
fillRect
(
0
,
0
,
200
,
200
);
context
.
fillStyle
=
'#ffffff'
;
context
.
font
=
'20px sans-serif'
;
context
.
textBaseline
=
'top'
;
context
.
fillText
(
"Player Ship - Static"
,
0
,
180
);
//drawShip
context
.
strokeStyle
=
'#ffffff'
;
context
.
beginPath
();
context
.
moveTo
(
10
,
0
);
context
.
lineTo
(
19
,
19
);
context
.
lineTo
(
10
,
9
);
context
.
moveTo
(
9
,
9
);
context
.
lineTo
(
0
,
19
);
context
.
lineTo
(
9
,
0
);
context
.
stroke
();
context
.
closePath
();
}
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.