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>- The canvas coordinate system starts at the top-left (0,0); x grows to the right and y grows downward.
- A game loop repeats forever: update the state (move things, check collisions), clear the screen, draw everything. Use
requestAnimationFrame, which runs once per screen refresh (usually about 60 times per second) and pauses in hidden tabs.
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);