CodeBlanks Logo Icon CodeBlanks

Drawing animation

JavaScript course · Expert · Lesson 46/63

Learn to set up a canvas animation loop with requestAnimationFrame.

The animation loop

Animation on the canvas works by erasing and redrawing on every frame. requestAnimationFrame tells the browser to call a function on the next frame.

A typical loop works like this: inside a draw function you first clear the screen with clearRect, draw the shape at the new position, update the position, and request the next frame with requestAnimationFrame(draw). This produces smooth motion.

Clearing with clearRect

If you do not clear the screen on each frame, old drawings stack up and leave a trail behind the ball. clearRect(0, 0, canvas.width, canvas.height) clears the whole surface.

The clear happens at the start of every draw call. Then the shape is drawn at the new position and the loop continues. This clear-and-redraw pattern is the basis of canvas animation.

Exercise Moving rectangle

Write a moving rectangle animation. Initialize with let x = 0. Define a draw function that clears the screen with ctx.clearRect(0, 0, canvas.width, canvas.height), draws the rectangle with ctx.fillRect(x, 10, 20, 20), advances with x += 2, and finally requests the next frame with requestAnimationFrame(draw).

Show example solution
let x = 0;
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(x, 10, 20, 20);
  x += 2;
  requestAnimationFrame(draw);
}
draw();

Test yourself

  1. What should happen on every frame in the animation loop?

    • Only add a new shape
    • Clear the screen and redraw
    • Only call requestAnimationFrame
    • Resize the canvas
    Show answer

    Clear the screen and redraw — Correct! Each frame clears the screen and redraws at the new position.

  2. Keep the loop going

    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillRect(x, 10, 20, 20);
      x += 2;
      ____(draw);
    }
    Show answer
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillRect(x, 10, 20, 20);
      x += 2;
      requestAnimationFrame(draw);
    }
  3. Match the animation loop

    requestAnimationFrame
    next frame
    clearRect
    clear screen
    draw
    draw function
    x += 2
    advance

All lessons in Expert