Skip to content
jshacks.dev
Browser

Confetti burst with canvas

Draw a short burst of confetti on a canvas with particles that move, fall and fade each frame using requestAnimationFrame. No library needed.

1 min read
Summarize in AI

A confetti burst is a few dozen particles with a velocity and gravity. Update them every frame, draw them, and stop when they are gone.

confetti.jsJavaScript
function confetti(canvas, count = 80) {
  const ctx = canvas.getContext('2d');
  const particles = Array.from({ length: count }, () => ({
    x: canvas.width / 2,
    y: canvas.height / 2,
    vx: (Math.random() - 0.5) * 12,
    vy: Math.random() * -10 - 4,
    size: 4 + Math.random() * 4,
    color: `hsl(${Math.random() * 360} 90% 60%)`,
    life: 1,
  }));

  function frame() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (const p of particles) {
      p.vy += 0.3;
      p.x += p.vx;
      p.y += p.vy;
      p.life -= 0.012;
      ctx.globalAlpha = Math.max(p.life, 0);
      ctx.fillStyle = p.color;
      ctx.fillRect(p.x, p.y, p.size, p.size);
    }
    if (particles.some((p) => p.life > 0)) requestAnimationFrame(frame);
    else console.log('confetti done');
  }
  requestAnimationFrame(frame);
}

confetti(document.querySelector('canvas'));
Text
confetti done

Gravity adds to vy each frame, so particles rise, slow, then fall. life fades them out, and the loop ends once all are invisible, so no frame callbacks keep running. The colours and trajectories use Math.random, so each burst looks different.

Frame-based motion runs faster on a 120 Hz screen, so scale by elapsed time if that matters. Skip the effect when prefers-reduced-motion: reduce matches.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.