Unit 7 · JavaScript

7.10.1Canvas basics and the game loop

In this section you build a browser game using the HTML <canvas> element and JavaScript. The four required skills are sprite sheet animation, key event handling, object colliders and anonymous functions. The scenario for the practical assessment will be given by your lecturer; the same techniques apply to any scenario (collect items, avoid enemies, shoot targets, reach a goal).

HTML
<canvas id='game' width='640' height='360' style='border:1px solid #000'></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');      // the 'pen' we draw with

ctx.fillStyle = 'tomato';
ctx.fillRect(50, 50, 100, 60);            // x, y, width, height
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Score: 0', 10, 25);         // text at x, y
ctx.beginPath();
ctx.arc(300, 100, 30, 0, Math.PI * 2);    // circle: x, y, radius, start, end
ctx.fill();
</script>
x grows to the righty growsdownward(0, 0)fillRect(50, 50, 100, 60)arc(300, 100, 30, …)(480, 240)(640, 360)<canvas width='640' height='360'>
Canvas coordinates start at the top-left corner; y increases downward
JavaScript
function loop() {
  update();                                      // 1. change positions, check collisions
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 2. erase old frame
  draw();                                        // 3. paint new frame
  requestAnimationFrame(loop);                   // 4. ask for next frame
}
requestAnimationFrame(loop);
1. update()move, check collisions2. clearRect()erase old frame3. draw()paint new frame4. requestAnimationFrame()ask for the next framerepeats about60 times a second
A game loop repeats update, clear and draw on every screen refresh