Advanced Canvas Animation — Web Animation

A particle (one piece of confetti) is an object { x, y, vx, vy, life, maxLife, opacity }: position, velocity, remaining life, starting life and opacity. Every…

300 pieces of confetti burst when the "Booking sent" toast appears, and all of them are redrawn on one <canvas> (an element you draw on with JavaScript) every frame. That is what advanced canvas means: many small things at once. Imagine a wedding committee preparing 300 chairs for guests:

The basic loop (clear, update, draw), dt and devicePixelRatio were covered in the Canvas API Basics and Canvas Animation lessons of the Creative Web track. Here we use them again. In short, dt is the time since the previous frame, in seconds.

One piece of confetti

A particle (here, one piece of confetti) is just an object with a position (x, y), a velocity (vx, vy, in px per second) and its remaining life (life, in seconds). Every frame, the particle moves by velocity × dt, and its life drops by dt. Its opacity falls with the ratio of its remaining life to its starting life (maxLife):

function createParticle(x, y, vx, vy, life) {
  return { x, y, vx, vy, life, maxLife: life, opacity: 1, alive: true };
}

function updateParticle(p, dt) {
  p.x += p.vx * dt;                              // move: velocity × time step
  p.y += p.vy * dt;
  p.life -= dt;                                  // life runs down
  p.opacity = Math.max(0, p.life / p.maxLife);   // fades, never below 0
  p.alive = p.life > 0;                          // no life left = dead
  return p;
}

This is the trace of its values, step by step, for createParticle(0, 0, 10, -5, 1): a particle at the point (0, 0), with vx 10, vy -5 and a life of 1 second.

Step dt x life opacity alive
just made 0 1 1 true
update 0.5 0 + 10 × 0.5 = 5 0.5 0.5 / 1 = 0.5 true
update again 0.6 11 -0.1 0 false

In the exercise, the particle system keeps the list of particles and a fixed capacity (the largest number of particles): createParticleSystem(2) takes two particles, and a third is refused. That fixed capacity is the basic idea of a pool.

The "Booking sent" confetti

This is the whole confetti. burst() sends 300 pieces out from the point (x, y), and frame() does the work of one frame:

const canvas = document.querySelector('.confetti');
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio || 1;            // sharp on retina screens
canvas.width = 320 * dpr; canvas.height = 200 * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

const COLORS = ['#15803d', '#4ade80', '#f59e0b'];
const pool = [];                                     // 300 "rented chairs", made once
for (let i = 0; i < 300; i++) pool.push({ x: 0, y: 0, vx: 0, vy: 0, life: 0, color: '' });
let active = 0;                                      // pool[0..active-1] are in use
let last = null;

function burst(x, y) {
  if (matchMedia('(prefers-reduced-motion: reduce)').matches) return; // no confetti
  for (active = 0; active < pool.length; active++) {
    const p = pool[active];
    p.x = x; p.y = y; p.vx = (Math.random() - 0.5) * 400; p.vy = -200 - Math.random() * 300;
    p.life = 1.2 + Math.random() * 0.8; p.color = COLORS[active % 3];
  }
  last = null; requestAnimationFrame(frame);
}

function frame(now) {
  const dt = last === null ? 0 : Math.min((now - last) / 1000, 0.1); // capped: a tab coming back
  last = now;
  ctx.clearRect(0, 0, 320, 200);                     // 1. clear
  for (let i = 0; i < active; ) {
    const p = pool[i];
    p.vy += 600 * dt; p.x += p.vx * dt; p.y += p.vy * dt; p.life -= dt; // 2. update
    if (p.life <= 0) { pool[i] = pool[active - 1]; pool[active - 1] = p; active--; continue; }
    ctx.fillStyle = p.color; ctx.fillRect(p.x - 4, p.y - 2, 8, 4);    // 3. draw
    i++;
  }
  if (active > 0) requestAnimationFrame(frame);      // stops by itself once all are dead
}

One trap: if burst() is called again before the first confetti is over, burst() starts a second requestAnimationFrame loop next to the old one. This happens, for example, when two bookings are sent one after the other. In Chromium 156, after three quick burst() calls, frame() ran 3 times per screen frame: three rounds of clear, update and draw for the same result. Keep the id of the scheduled frame (the number requestAnimationFrame returns). Then cancel the old one before starting again:

let rafId = 0;                                       // id of the next scheduled frame

// at the end of burst(), replace the requestAnimationFrame line:
cancelAnimationFrame(rafId);                         // cancel the old loop, if any
last = null; rafId = requestAnimationFrame(frame);

// at the end of frame():
if (active > 0) rafId = requestAnimationFrame(frame);

With this change, frame() runs once per screen frame, however many times burst() is called.

Object pools: when they help

Take a guess first: 300 pieces of confetti burst every 2 seconds for 6 seconds. Version A makes 300 new objects per burst. Version B uses a pool of 300 objects that it reuses. How many times does the garbage collector run in each?

We ran three versions in Chromium 147 (an M1 Pro laptop, 120 Hz screen), with a 300-piece burst every 2 seconds for 6 seconds. Then we counted the minor GCs (small garbage collections in V8, the JavaScript engine of Chromium) and their times in the Performance recording:

Version Minor GCs Total Longest With a 4x slower CPU
Pool of 300 objects 6 1.6 to 3.4 ms 1.8 ms 5.4 to 6.8 ms
300 new objects per burst, filter() every frame 6 3.8 to 4.0 ms 1.9 ms 6.0 to 6.8 ms
plus a new { x, y } object and colour string per piece per frame 22 to 23 5.6 to 7.3 ms 0.8 ms 22.5 to 25.8 ms

Versions A and B give the same, 6 times. Those six GCs come from the page's own work, not from the confetti: 300 objects per burst are too few to make V8 work harder. What raises the GC count almost 4 times is making new objects and strings per piece per frame (the third version): 300 pieces × 120 frames × 2 (one object and one string) = 72,000 a second. So a pool is not a magic charm: it does not always make things faster. Use one when you make thousands of objects a second, especially for slow phones, and measure first in the DevTools Performance tab ("Minor GC").

Drawing cost: shadows, filters, sprites

The same code can be cheap in one browser and expensive in another. shadowBlur gives each piece a soft shadow, and ctx.filter gives an effect such as blur. We drew 300 pieces for 2 seconds on the same laptop:

How it draws Chromium 147 Firefox 146 WebKit 26.4 (60 Hz)
plain fillRect 120 fps, JS 0.3 ms/frame 120 fps, 0.6 ms 60 fps, 0.4 ms
shadowBlur = 6 120 fps, 0.3 ms 36 to 49 fps, 20 to 27 ms 60 fps, 0.3 ms
ctx.filter = 'blur(1px)' 19 to 21 fps, 0.5 ms 109 to 118 fps, 8 to 9 ms not supported, silently ignored
pre-rendered sprite (shadow stamped once) 102 to 112 fps, 0.4 ms 120 fps, 3.3 ms 60 fps, 0.4 ms

In Chromium the GPU draws the shadow, so shadowBlur stays at 120 fps. What makes the GPU work hard is a filter per piece: the JavaScript stays light, but frames still drop to 20 fps. In Firefox the shadow is computed on the main thread, so frames drop to 36 to 49 fps. ctx.filter in Safari is only behind a flag (a test setting you have to turn on yourself), since Safari 18. A sprite is the safe choice in all three browsers: draw the piece and its shadow once to another canvas, then stamp that picture with drawImage in every frame:

const sprite = new OffscreenCanvas(20 * dpr, 16 * dpr);   // or document.createElement('canvas')
const s = sprite.getContext('2d');
s.setTransform(dpr, 0, 0, dpr, 0, 0);
s.shadowColor = 'rgba(0, 0, 0, 0.35)'; s.shadowBlur = 6;  // the shadow is computed once, here
s.fillStyle = '#15803d'; s.fillRect(6, 6, 8, 4);

ctx.drawImage(sprite, p.x - 10, p.y - 8, 20, 16);         // every piece, every frame: just a stamp

OffscreenCanvas in a Web Worker

OffscreenCanvas is a canvas with no element on the page. With transferControlToOffscreen(), a canvas on the page is handed to a Web Worker (another thread for JavaScript), and the worker does the drawing:

// the page
const off = document.querySelector('.confetti').transferControlToOffscreen();
const worker = new Worker('confetti-worker.js');
worker.postMessage({ canvas: off, dpr: devicePixelRatio, reduce: matchMedia('(prefers-reduced-motion: reduce)').matches }, [off]);

// confetti-worker.js
onmessage = (e) => {
  const ctx = e.data.canvas.getContext('2d');   // the same loop, with the worker's own requestAnimationFrame
};

Supported in Chrome 69, Firefox 105 and Safari 16.4 for the 2D context. For WebGL (a way to draw through the GPU), Safari supports it from version 17. We blocked the main thread for 500 ms in the middle of a burst. The worker kept drawing, 60 frames in Chromium and Firefox and 28 in WebKit (60 Hz), while the main-thread loop drew 0 frames. The price: a worker cannot touch the DOM (the structure of elements on the page) or matchMedia. So everything the worker needs (size, dpr, "Reduce motion") is sent with postMessage.

Stop when nobody is watching

When to move to a library: PixiJS

Hundreds to thousands of sprites moving at once are lighter when the GPU draws them through WebGL. PixiJS 8.22 uses WebGL by default, then WebGPU (the newer successor of WebGL), and Canvas 2D as the last fallback. For one burst of 300 pieces, Canvas 2D is enough and adds nothing to download.

⚠️ Confetti that is heavy or won't die

TL;DR: A particle (one piece of confetti) is an object { x, y, vx, vy, life, maxLife, opacity }: position, velocity, remaining life, starting life and opacity. Every frame, x += vx * dt (dt = the time since the previous frame), life -= dt, opacity = Math.max(0, life / maxLife) and alive = life > 0. For example, a particle at x 0 with vx 10 and a life of 1 second, after a dt of 0.5: x = 0 + 10 × 0.5 = 5 and opacity 0.5. After another 0.6 seconds, it is dead. The canvas loop: clear, update, draw with requestAnimationFrame, dt capped at 0.1 seconds, and devicePixelRatio for sharpness. The loop stops by itself when every piece is dead, and there is no confetti when "Reduce motion" is on. A pool is a fixed number of objects made once and reused (a dead piece is swapped to the end). In Chromium 147, 300 new objects per burst still gave 6 minor GCs (small memory clean-ups), like the pool. New objects per piece per frame raised that to 22 to 23. Drawing cost differs per browser. shadowBlur (a soft shadow) costs 20 to 27 ms a frame in Firefox. ctx.filter (an effect such as blur) runs at 20 fps in Chromium and is unsupported in Safari. A pre-rendered sprite (drawn once, then stamped) is safe in all three browsers. OffscreenCanvas + transferControlToOffscreen() (Chrome 69, Firefox 105, Safari 16.4) moves the drawing work to a Web Worker (a separate thread). With the main thread blocked for 500 ms, the worker still drew 60 frames in Chromium and Firefox. For hundreds to thousands of sprites, use the PixiJS library (WebGL, then WebGPU, then Canvas 2D).

⚡ One piece of confetti

Write:

function updateParticle(p, dt) {
  p.x += p.vx * dt;                              // move: velocity × time step
  p.y += p.vy * dt;
  p.life -= dt;                                  // life runs down
  p.opacity = Math.max(0, p.life / p.maxLife);   // fades, never below 0
  p.alive = p.life > 0;                          // no life left = dead
  return p;
}

Meaning: A particle (here, one piece of confetti) is just an object with a position (x, y), a velocity (vx, vy) and its remaining life (life). dt is the time since the previous frame, in seconds. Every frame, the particle moves by velocity × dt, its life drops, and its opacity falls with it. When its life reaches zero, alive becomes false.

⚡ Clear, update, draw

Meaning: Every frame keeps the same pattern: clear the canvas, update the state of each piece, draw, then repeat with requestAnimationFrame. A dead piece is swapped to the end, out of the list of live pieces. The loop stops by itself once every piece is dead.

⚡ A pool is no charm

Guess first: a pool is a set of objects made once, then reused. 300 pieces of confetti burst every 2 seconds for 6 seconds. Version A makes 300 new objects per burst, version B reuses a pool of 300 objects. How many times does the garbage collector (GC, the cleaner of unused objects) run in each?

The same, 6 times. Almost 4 times as many GCs come from new objects and strings per piece per frame: 22 to 23 times.

Meaning: A pool does not always make things faster. Use a pool when you make thousands of objects a second, and measure first in the Performance tab.

⚡ Draw once, stamp many times

Meaning: shadowBlur (a soft shadow) and ctx.filter (an effect such as blur) per piece cost differently in every browser. A sprite, a piece drawn once and then stamped with drawImage, is safe in Chromium, Firefox and Safari. With OffscreenCanvas in a Web Worker (a separate thread), the worker still draws 60 frames in Chromium and Firefox while the main thread is blocked for 500 ms.

What you will learn