Add Canvas Confetti Effects to Any Website with Vanilla Confetti

Category: Animation , Javascript | April 28, 2025
Author:devpotatoes
Views Total:300 views
Official Page:Go to website
Last Update:April 28, 2025
License:MIT

Preview:

Add Canvas Confetti Effects to Any Website with Vanilla Confetti

Description:

Vanilla Confetti is a lightweight JavaScript library that creates canvas-based confetti animations for web projects.

It takes a target canvas element and renders falling confetti particles based on a configuration object.

Features:

  • Zero Dependencies: Pure vanilla JavaScript, no external libraries needed.
  • Customizable: Control colors, speed, quantity, size, and opacity.
  • Looping Option: Set confetti to fall continuously.
  • Multiple Shapes: Renders rectangles, circles, and simple triangles.
  • Simple Integration: Requires minimal setup with HTML canvas and JS module import.
  • Responsive: Automatically resizes the canvas animation area with the window.

See it in action:

How to use it:

1. Download the package and import ‘generateConfetti’ into your JS.

import { generateConfetti } from "./vanillaConfetti.min.js";

2. Create an empty canvas element where the confetti will be rendered.

<canvas id="vanillaConfettiCanvas"></canvas>

3. Make the canvas element cover the area you want.

#vanillaConfettiCanvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999; /* Adjust as needed */
  pointer-events: none; /* Allows clicks to pass through */
}

4. Define your configuration object and call the function.

const confettiConfig = {
  // options here
};
const canvasId = "vanillaConfettiCanvas";
// Trigger the confetti!
// Could be inside an event listener (e.g., button click)
document.getElementById('celebrateButton').addEventListener('click', () => {
  generateConfetti(confettiConfig, canvasId); // Pass canvasId if not default
});
// Or just run it immediately on load
// generateConfetti(confettiConfig);

5. Available configuration options.

  • colorsArray (Array): Strings representing CSS colors (hex, rgb, rgba). A random color is picked for each particle.
  • velocity (Number): Affects the downward acceleration (gravity). Higher means faster acceleration.
  • quantity (Number): Total number of confetti pieces generated. Watch performance here – thousands can slow things down.
  • minSize / maxSize (Number): Pixel range for the size of each piece.
  • minOpacity / maxOpacity (Number): 0-1 range controlling transparency. Combined with a subtle random factor during animation.
  • infiniteLoop (Boolean): If true, confetti resets to the top when it falls off the bottom. If false (default), it stops after the initial batch falls.
const confettiConfig = {
  colorsArray: ["rgba(255, 255, 163, 1)", "rgba(0, 0, 185, 1)"],
  velocity: 0.05,
  quantity: 500,
  minSize: 8,
  maxSize: 24,
  minOpacity: 0.5,
  maxOpacity: 1,
  infiniteLoop: false
};

You Might Be Interested In:


Leave a Reply