Lazo Lab Sign up

Web Development / JavaScript

Lesson 24 of 30

Canvas games

The <canvas> element lets JavaScript draw pixels. A game loop with requestAnimationFrame redraws about 60 times a second.

Key points

  • ctx.fillRect(x, y, w, h)
  • requestAnimationFrame(loop)
  • Clear, update, draw each frame
const ctx = canvas.getContext("2d");
function loop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(x++, 50, 20, 20);
  requestAnimationFrame(loop);
}
loop();
Watch a video on thisOpens YouTube search results for “Canvas games” in a new tab

Quiz · +10 XP

Which function schedules the next frame of an animation?

Log in to save progress and earn XP.