HTML and CSS Reference
In-Depth Information
The drawScreen() function code to add this extra “thrust” graphic is very simple; see
Example 8-3 .
Example 8-3. Drawing the player ship with thrust
function drawScreen() {
// draw background and text
context.fillStyle = '#000000';
context.fillRect(0, 0, 200, 200);
context.fillStyle = '#ffffff';
context.font = '20px _sans';
context.textBaseline = 'top';
context.fillText ("Player Ship - Thrust", 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);
//draw thrust
context.moveTo(8,13);
context.lineTo(11,13);
context.moveTo(9,14);
context.lineTo(9,18);
context.moveTo(10,14);
context.lineTo(10,18);
context.stroke();
context.closePath();
}
Animating on the Canvas
The player ship we just created has two frames (static and thrust), but we can only
display a single frame at a time. Our game will need to switch out the frame of animation
based on the state of the player ship, and it will need to run on a timer so this animation
can occur. Let's take a quick look at the code necessary to create our game timer.
Game Timer Loop
Games on HTML5 Canvas require the use of the repeated update/render loop to sim-
ulate animation. We do this by using the setInterval() JavaScript function, which will
repeatedly call a function of our choosing at millisecond intervals. Each second of game/
animation time is made up of 1,000 milliseconds. If we want our game to run at 30
update/render cycles per second, we call this a 30 frames per second (FPS) rate. To run
Search WWH ::




Custom Search