Canvas Animation — Creative Web

Canvas animation is a requestAnimationFrame(frame) loop: every frame clear (clearRect), update, then redraw everything, still parts included…

In the Canvas API Basics lesson, the steam area above the cup of the coffee print was left empty on purpose. Now we make the steam rise. The way to do it isn't moving the picture, it's redrawing the whole picture many times a second, a little different each time. Like a flipbook: every page is drawn in full, the cup too, even though only the steam moves a little. Flip it fast and the steam seems to rise.

The loop with requestAnimationFrame

requestAnimationFrame(fn) asks the browser to call fn right before it draws the next frame. A frame is one picture shown on the screen. The browser calls it as often as the screen refreshes: 60 times a second on a 60 Hz screen, 120 times on a 120 Hz screen. To make a loop, the function asks for the next frame again:

function frame(now) {
  // now: this frame's time in milliseconds, sent by the browser
  // ...update and draw...
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

Why not setInterval(fn, 16)? An interval isn't in step with the screen, so sometimes two updates land in one frame and the motion stutters. In a hidden tab the interval keeps running (the browser limits it to once a second at most), while requestAnimationFrame stops.

One frame: clear, update, redraw

A canvas only keeps pixels; there's no "steam object" to move. So every frame:

  1. Clear the old frame: ctx.clearRect(0, 0, 300, 300) makes the whole canvas transparent again.
  2. Update every particle's position.
  3. Redraw everything: the print too, because clearRect wiped it as well.

Without step 1, new steam is drawn on top of old steam, and what you see is a thick white trail, not rising steam. With clearRect but without redrawing the print, the cup disappears and only steam is left on an empty canvas. If your first drawing paints the whole canvas (the black fabric, fillRect(0, 0, 300, 300)), that fabric already covers the old frame, and clearRect isn't required.

Moving per frame vs moving per second

Raka writes y -= 1 every frame, and on his laptop (a 60 Hz screen) the steam rises just right. Before reading on, guess: on a phone with a 120 Hz screen, does the steam rise faster, the same, or slower?

Moving per frame (y -= 1) shifts 1 px every time the function is called. Its distance per second follows the number of frames. Moving per second uses dt (delta time): how many seconds have passed since the previous frame, worked out from now. Raka's steam rises 60 px per second and lives 1.5 seconds, so it rises 90 px (from y 112 to y 22).

Screen Time between frames y -= 1 per frame y -= 60 * dt
30 Hz 33.3 ms 30 px/second, reaches the top in 3 seconds 2 px per frame, 60 px/second, 1.5 seconds
60 Hz 16.7 ms 60 px/second, 1.5 seconds 1 px per frame, 60 px/second, 1.5 seconds
120 Hz 8.3 ms 120 px/second, 0.75 seconds 0.5 px per frame, 60 px/second, 1.5 seconds

On a 120 Hz phone, per-frame steam rises twice as fast. With dt, a faster screen only gives smaller steps, so the speed is the same on every screen.

Coffee steam

let last = null;  // previous frame's time (ms)
let steam = [];   // steam particles still alive
let wait = 0;     // seconds until the next particle is born

function frame(now) {
  if (last === null) last = now;
  const dt = Math.min((now - last) / 1000, 0.1); // seconds, at most 0.1
  last = now;

  // update: move the ones already there
  for (const p of steam) {
    p.y -= 60 * dt;   // rise 60 px per second
    p.x += p.vx * dt; // drift sideways
    p.age += dt;
  }
  steam = steam.filter((p) => p.age < 1.5);
  // then give birth to a new one
  wait -= dt;
  if (wait <= 0) {
    steam.push({ x: 120 + Math.random() * 60, y: 112, age: 0, vx: (Math.random() - 0.5) * 12 });
    wait += 0.1; // 10 particles per second
  }

  // redraw
  ctx.clearRect(0, 0, 300, 300);
  drawPrint(); // fabric, cup and lettering from the previous lesson
  for (const p of steam) {
    const t = p.age / 1.5; // 0 just born, 1 about to vanish
    ctx.globalAlpha = 0.6 * (1 - t);
    ctx.beginPath();
    ctx.arc(p.x, p.y, 6 + 8 * t, 0, Math.PI * 2);
    ctx.fillStyle = '#f5e6c8';
    ctx.fill();
  }
  ctx.globalAlpha = 1;

  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

Bouncing off the edges

Something moved every frame without an edge check keeps going past the canvas edge and never stops. Something that bounces flips its velocity when it touches an edge. Take a coffee bean with radius 20 on a canvas 400 tall, starting at y 370, dy = 4 per frame:

y += dy;                                          // move first
if (y + radius > 400 || y - radius < 0) dy *= -1; // then check the edge
Frame y after moving y + radius More than 400? dy
1 374 394 no 4
2 378 398 no 4
3 382 402 yes, flip -4
4 378 398 no -4

dy *= -1 only flips the axis that touched an edge; the x axis stays as it is. In the exercise, one call to update() is one frame.

Hidden tabs and "reduce motion"

Most browsers stop requestAnimationFrame in hidden tabs and hidden iframes, to save battery. Safari on iPhone also limits it to 30 frames per second in Low Power Mode, and in iframes from another site that the user hasn't touched yet. Moving per second stays right at 30 fps. But when the tab comes back after 5 seconds, now - last is 5,000 ms: without Math.min, dt becomes 5 seconds, every steam particle is past 1.5 seconds old and they all vanish at once. With Math.min(..., 0.1), that frame only moves 0.1 seconds forward.

Some people get dizzy or sick from motion and turn on "Reduce motion" in their system settings. The browser tells you through a media query:

const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
if (reduceMotion) drawOneStillFrame(); // still steam, plus a Play button
else requestAnimationFrame(frame);

An animation that starts on its own and runs longer than 5 seconds also needs a Pause button (WCAG 2.2.2). Pausing means you stop calling requestAnimationFrame, and when it resumes, set last = null again.

⚠️ Why does the steam race, pile up or jump?

TL;DR: Canvas animation is a requestAnimationFrame(frame) loop: every frame clear (clearRect), update, then redraw everything, still parts included. requestAnimationFrame runs as often as the screen refreshes and passes a timestamp now; work out dt = (now - last) / 1000 and move by speed × dt, so the steam rises 60 px per second at 30, 60 or 120 Hz, while y -= 1 per frame is twice as fast at 120 Hz. Bouncing: move, then if y + radius > height or y - radius < 0, dy *= -1. Browsers stop rAF in hidden tabs, so cap dt with Math.min(dt, 0.1). Respect prefers-reduced-motion and offer a Pause button.

⚡ A loop in step with the screen

Write:

function frame(now) {
  // ...update and draw...
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

Meaning: requestAnimationFrame calls frame right before the browser draws the next frame, as often as the screen refreshes. To make a loop, frame asks for the next frame again.

⚡ Clear, update, redraw

Guess first: without clearRect, what does the steam look like?

A thick white trail. New steam is drawn on top of old steam, because a canvas only keeps pixels.

Meaning: Every frame: clear the old frame with ctx.clearRect(0, 0, 300, 300), update the positions, then redraw everything, the print too, because clearRect wiped it as well.

⚡ Move per second, not per frame

Write:

const dt = Math.min((now - last) / 1000, 0.1);
last = now;
p.y -= 60 * dt;
Guess first: with y -= 1 every frame, does the steam rise faster, the same, or slower on a 120 Hz phone?

Twice as fast, because the function is called 120 times a second.

Meaning: dt is the seconds since the previous frame. Speed × dt makes the steam rise 60 px per second on any screen, and Math.min keeps a tab that was hidden for a long time from jumping.

⚡ Bouncing off the edges

Write:

y += dy;
if (y + radius > 400 || y - radius < 0) dy *= -1;

Meaning: Move first, then check the edge with the radius, because what touches the edge is the bean's rim. dy *= -1 only flips the axis that touched an edge.

What you will learn