JavaScript
Challenge - Canvas game flow
Build a ball-and-basket game with canvas, requestAnimationFrame and collision detection.
Canvas game flow
In this challenge you will draw a ball-and-basket game on a <canvas>. First you get the 2D drawing context with canvas.getContext('2d').
The game loop is set up with requestAnimationFrame(loop); the browser calls loop on each frame. Inside loop you clear the screen with ctx.clearRect(0, 0, w, h), update positions and call requestAnimationFrame(loop) again.
For collision detection you check whether the two bounding boxes overlap; when they do, the ball enters the basket.
Exercise Game loop and collision
First get the 2D context with canvas.getContext('2d'). Then write a loop(timestamp) function: it must call ctx.clearRect(0, 0, canvas.width, canvas.height) and schedule itself again with requestAnimationFrame(loop). For collision detection, add an if that checks whether the bounding boxes of the ball and the basket overlap and runs score++ when they do.
Show example solution
Start with const ctx = canvas.getContext('2d');. Then write function loop(timestamp) { ctx.clearRect(0, 0, canvas.width, canvas.height); if (ball.x < basket.x + basket.w) { score++; } ball.x += 1; requestAnimationFrame(loop); }.
Example solution:
const ctx = canvas.getContext('2d');
let score = 0;
const ball = { x: 10, y: 10, size: 8 };
const basket = { x: 80, y: 60, w: 30, h: 20 };
function loop(timestamp) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (ball.x < basket.x + basket.w && ball.x + ball.size > basket.x) {
score++;
}
ctx.fillRect(ball.x, ball.y, ball.size, ball.size);
ctx.fillRect(basket.x, basket.y, basket.w, basket.h);
ball.x += 1;
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Test yourself
-
What does requestAnimationFrame do?
function loop(t) {
ctx.clearRect(0, 0, w, h);
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
- It sets a one-shot timer
- It draws directly to the screen
- It adds an event listener
- It calls the given function on the next frame
Show answer
It calls the given function on the next frame — Correct! requestAnimationFrame schedules the given function to run on the next frame, before the browser repaints.
-
Get the 2D context
const canvas = document.querySelector('canvas');
const ctx = canvas.____('2d');
Show answer
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
-
Match the canvas game concepts
- getContext('2d')
- 2D context
- requestAnimationFrame
- Frame scheduler
- clearRect
- Clear screen
- ctx.fillRect
- Draw rectangle
Next lesson: Challenge - Secure app