canvas-confetti

repository·master·Indexed 11 days ago

https://github.com/catdad/canvas-confetti

A performant client-side library for creating confetti animations on an HTML canvas. Version 1.9.4 features a primary `confetti()` API for launching bursts, support for custom shapes via `shapeFromPath()` and `shapeFromText()`, and the ability to respect user motion preferences with the `disableForReducedMotion` option.

Tokens
3.3K
Snippets
16
Records
19
Agent score
46%

What's inside canvas-confetti

  1. Install canvas-confetti via CDN

    master

    Include the library directly in your HTML page by adding a <script> tag pointing to the JSDelivr CDN. Ensure you use the latest version available.

    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/dist/confetti.browser.min.js"></script>
  2. Respect user motion preferences with disableForReducedMotion

    master

    To support users who have enabled prefers-reduced-motion in their system settings, use the disableForReducedMotion option. When this option is active, confetti animations will be suppressed for those users to avoid chaotic motion that might cause discomfort.

    This option is currently disabled by default.

  3. Launch confetti from a specific origin

    master

    Use the origin option to control where the confetti starts. The origin object takes x and y coordinates (typically normalized between 0 and 1).

    confetti({
      particleCount: 100,
      startVelocity: 30,
      spread: 360,
      origin: {
        x: Math.random(),
        // since they fall down, start a bit higher than random
        y: Math.random() - 0.2
      }
    });
  4. Continuously launch confetti from multiple directions

    master

    Because calling confetti multiple times simply adds to the total number of particles in the air, you can use requestAnimationFrame to create continuous effects. This example launches confetti from both the left and right edges of the screen for a set duration.

    // do this for 30 seconds
    var duration = 30 * 1000;
    var end = Date.now() + duration;
    
    (function frame() {
      // launch a few confetti from the left edge
      confetti({
        particleCount: 7,
        angle: 60,
        spread: 55,
        origin: { x: 0 }
      });
      // and launch a few from the right edge
      confetti({
        particleCount: 7,
        angle: 120,
        spread: 55,
        origin: { x: 1 }
      });
    
      // keep going until we are out of time
      if (Date.now() < end) {
        requestAnimationFrame(frame);
      }
    }());
  5. Create a custom confetti instance with `confetti.create()`

    master

    Use confetti.create(canvas, [globalOptions]) to limit confetti to a specific <canvas> element. This is useful for contained animations.

    Global Options:

    • resize (Boolean, default: false): If true, allows the library to set the canvas image size and keep it responsive to window changes.
    • useWorker (Boolean, default: false): If true, uses an asynchronous web worker for rendering.
      • Warning: If useWorker: true is set, the canvas is transferred to the worker. You must not attempt to manipulate the canvas on the main thread, or it will throw an error.
    • disableForReducedMotion (Boolean, default: false): Respects user motion preferences for this specific instance.

    Note: Persist the returned function and avoid re-initializing the same canvas multiple times.

    var myCanvas = document.createElement('canvas');
    document.body.appendChild(myCanvas);
    
    var myConfetti = confetti.create(myCanvas, {
      resize: true,
      useWorker: true
    });
    
    myConfetti({
      particleCount: 100,
      spread: 160
    });
  6. Use the `confetti()` function to launch confetti

    master

    The primary API is the confetti() function. It launches a burst of confetti and returns a Promise that resolves when the animation is complete. If window.Promise is unavailable (e.g., in IE), it returns null.

    If you call confetti() multiple times before the previous animation finishes, the library reuses the same canvas and continues the existing animation with the new particles. The returned promise will resolve once all active animations are done.

    // Basic usage
    confetti();
    
    // Using options
    confetti({
      particleCount: 100,
      spread: 70,
      origin: { x: 0.5, y: 0.5 }
    });
  7. Stop animations with `confetti.reset()`

    master

    The reset() method stops all active animations and clears all confetti from the canvas. It also immediately resolves any outstanding promises.

    • For the global instance, call confetti.reset().
    • For an instance created via confetti.create(), call .reset() on the returned function.
    // Reset global confetti
    confetti();
    setTimeout(() => {
      confetti.reset();
    }, 100);
    
    // Reset a custom instance
    var myConfetti = confetti.create(myCanvas, { resize: true });
    myConfetti();
    setTimeout(() => {
      myConfetti.reset();
    }, 100);
  8. Create custom shapes with `confetti.shapeFromPath()`

    master

    Use confetti.shapeFromPath({ path, matrix? }) to create a custom shape from an SVG Path string.

    Caveats:

    • All paths are filled (stroke is not supported).
    • Paths are limited to a single color.
    • For performance, it is recommended to calculate the matrix once in development and cache it for production.
    • Requires browser support for Path2D.

    Pass the returned Shape object into the shapes array in your confetti() options.

    var triangle = confetti.shapeFromPath({ path: 'M0 10 L5 0 L10 10z' });
    
    confetti({
      shapes: [triangle]
    });