react-confetti

repository·develop·Indexed 23 days ago

https://github.com/alampros/react-confetti

A React component for high-performance confetti animations using HTML5 Canvas. Version 6.4.0 provides the ReactConfetti component and a Confetti class for managing animations, allowing customization of physics (gravity, wind, friction), appearance (colors, opacity, custom shapes via drawShape), and lifecycle through the IConfettiOptions interface.

Tokens
6K
Snippets
6
Records
12
Agent score
83%

What's inside react-confetti

  1. Use react-confetti with window resizing

    develop

    The <Confetti /> component uses width and height props to define the <canvas> dimensions. While these default to the initial window dimensions, they do not automatically respond to window resize events. To ensure the confetti always covers the viewport, it is recommended to provide these dimensions manually using a hook like useWindowSize from react-use.

    import React from 'react'
    import { useWindowSize } from 'react-use'
    import Confetti from 'react-confetti'
    
    export default () => {
      const { width, height } = useWindowSize()
      return (
        <Confetti
          width={width}
          height={height}
        />
      )
    }
  2. Draw custom confetti shapes with `drawShape()`

    develop

    You can customize the shape of each confetti particle by providing a drawShape function. This function receives the CanvasRenderingContext2D as its first argument and is called with the Particle as the this context. If omitted, the component defaults to a random selection of squares, circles, or strips.

    <Confetti
      drawShape={ctx => {
        ctx.beginPath()
        for(let i = 0; i < 22; i++) {
          const angle = 0.35 * i
          const x = (0.2 + (1.5 * angle)) * Math.cos(angle)
          const y = (0.2 + (1.5 * angle)) * Math.sin(angle)
          ctx.lineTo(x, y)
        }
        ctx.stroke()
        ctx.closePath()
      }}
    />
  3. Reference the Confetti component props

    develop

    The <Confetti /> component accepts the following props to control the animation, appearance, and physics of the confetti:

    | Property             | Type                                                                                                   | Default                                                                                                                 | Description                                                                                                                            |
    | ----------------     | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
    | `width`              | `Number`                                                                                               | `window.innerWidth \|\| 300`                                                                                             | Width of the `<canvas>` element.                                                                                        |
    | `height`             | `Number`                                                                                               | `window.innerHeight \|\| 200`                                                                                            | Height of the `<canvas>` element.                                                                                       |
    | `numberOfPieces`     | `Number`                                                                                               | 200                                                                                                                     | Number of confetti pieces at one time.                                                                                 |
    | `confettiSource`     | `{ x: Number, y: Number, w: Number, h: Number }`                                                      | `{x: 0, y: 0, w: canvas.width, h:0}`                                                                                     | Rectangle where the confetti should spawn. Default is across the top.                                                   |
    | `friction`           | `Number`                                                                                               | 0.99                                                                                                                    |                                                                                                                        |
    | `wind`               | `Number`                                                                                               | 0                                                                                                                      |                                                                                                                        |
    | `gravity`            | `Number`                                                                                               | 0.1                                                                                                                     |                                                                                                                        |
    | `initialVelocityX`   | `Number \| { min: Number, max: Number }`                                                               | 4                                                                                                                      | Range of values between which confetti is emitted horizontally, positive numbers being rightward, and negative numbers being leftward. Giving a number `x` is equivalent to giving a range `{ min: -x, max: x }`. |
    | `initialVelocityY`   | `Number \| { min: Number, max: Number }`                                                               | 10                                                                                                                     | Range of values between which confetti is emitted vertically, positive numbers being downward, and negative numbers being upward. Giving a number `y` is equivalent to giving a range `{ min: -y, max: 0 }`.|
    | `colors`             | `String[]`                                                                                             | `['#f44336'`, `'#e91e63'`, `'#9c27b0'`, `'#673ab7'`, `'#3f51b5'`, `'#2196f3'`, `'#03a9f4'`, `'#00bcd4'`, `'#009688'`, `'#4CAF50'`, `'#8BC34A'`, `'#CDDC39'`, `'#FFEB3B'`, `'#FFC107'`, `'#FF9800'`, `'#FF5722'`, `'#795548']` | All available Colors for the confetti pieces.                                                                                           |
    | `opacity`            | `Number`                                                                                               | 1.0                                                                                                                     |                                                                                                                        |
    | `recycle`            | `Bool`                                                                                                 | true                                                                                                                    | Keep spawning confetti after `numberOfPieces` pieces have been shown.                                                               |
    | `run`                | `Bool`                                                                                                 | true                                                                                                                    | Run the animation loop                                                                                                                 |
    | `frameRate`          | `Number \| undefined`                                                                  | undefined                                                                                                               | The capped frame rate of the animation.                                                                                               |
    | `tweenDuration`      | `Number`                                                                                               | 5000                                                                                                                     | How fast the confetti is added                                                                                                        |
    | `tweenFunction`      | `(currentTime: number, currentValue: number, targetValue: number, duration: number, s?: number) => number` | easeInOutQuad                                                                                                           | See [tween-functions](https://github.com/chenglou/tween-functions)                                                                     |
    | `drawShape`          | `(context: CanvasRenderingContext2D) => void`                                                              | `undefined`                                                                                                             | See below                                                                                                                             |
    | `onConfettiComplete` | `(confetti: Confetti) => void`                                                                             | `undefined`                                                                                                             | Called when all confetti has fallen off-canvas.                                                                                         |
  4. Use the ReactConfetti component

    develop

    The ReactConfetti component is the primary way to render confetti in a React application. It renders a <canvas> element that covers its container (defaulting to absolute positioning with pointer-events: none).

    To use it, import ReactConfetti and pass configuration options. The component accepts all standard HTMLCanvasElement attributes as well as specific confetti configuration props defined by IConfettiOptions.

  5. Configure ReactConfetti via Props

    develop

    The ReactConfetti component accepts two categories of props:

    1. Confetti Options: Props that control the confetti behavior (e.g., numberOfPieces, confettiSource, drawShape, onConfettiComplete, frameRate). These are typed via IConfettiOptions.
    2. Canvas Attributes: Standard React.CanvasHTMLAttributes<HTMLCanvasElement> props (e.g., style, id, className).

    Note: The component automatically applies a default style of position: absolute, top: 0, left: 0, bottom: 0, right: 0, zIndex: 2, and pointerEvents: 'none' to ensure the canvas overlays the content without interfering with user interactions, unless overridden via the style prop.

  6. Use the Confetti class to manage animations

    develop

    The Confetti class is the primary controller for the confetti animation. It requires an HTMLCanvasElement and an optional configuration object.

    Initialization

    Pass a canvas element and a partial options object to the constructor. The class will automatically merge your options with the confettiDefaults.

    Controlling the Animation

    • Update Options: You can update the animation behavior at runtime by setting the options property on the instance. This will trigger updates to the internal generator and handle state changes for run and recycle.
    • Stop: Call .stop() to set run: false and cancel the current requestAnimationFrame loop.
    • Reset: Call .reset() to clear all currently generated particles and reset the particle count to zero.

    Custom Shapes

    To use custom shapes, provide a drawShape function in your options. This function receives the CanvasRenderingContext2D and is responsible for drawing the confetti piece.

  7. Configure Confetti via IConfettiOptions

    develop

    The IConfettiOptions interface defines all available configuration properties for the confetti animation. You can pass a partial object of these options to the Confetti constructor to customize the behavior, appearance, and physics of the confetti.

    Physics and Movement

    • friction: Slows movement of pieces. Lower numbers result in slower confetti (default: 0.99).
    • wind: Blows confetti along the X axis (default: 0).
    • gravity: How fast it falls in pixels per frame (default: 0.1).
    • initialVelocityX: Horizontal emission speed. Can be a number or an object { min: number; max: number } (default: 4).
    • initialVelocityY: Vertical emission speed. Can be a number or an object { min: number; max: number } (default: 10).

    Appearance and Quantity

    • numberOfPieces: Maximum number of confetti pieces to render (default: 200).
    • colors: An array of color strings to choose from.
    • opacity: Opacity of the confetti (default: 1).
    • drawShape: An optional function to render custom shapes using a CanvasRenderingContext2D.

    Lifecycle and Control

    • recycle: If true, when a piece goes offscreen, a new one is emitted. If false, the animation stops after numberOfPieces are emitted (default: true).
    • run: If false, the animation loop is stopped (default: true).
    • onConfettiComplete: A callback function triggered when all confetti has fallen off-canvas.
    • tweenDuration: Milliseconds taken to spawn numberOfPieces (default: 5000).
    • tweenFunction: The function controlling the spawn rate (default: easeInOutQuad).
    export interface IConfettiOptions {
      width: number
      height: number
      numberOfPieces: number
      friction: number
      wind: number
      gravity: number
      initialVelocityX: { min: number; max: number } | number
      initialVelocityY: { min: number; max: number } | number
      colors: string[]
      opacity: number
      recycle: boolean
      run: boolean
      frameRate?: number
      debug: boolean
      confettiSource: IRect
      tweenFunction: (currentTime: number, currentValue: number, targetValue: number, duration: number, s?: number) => number
      tweenDuration: number
      drawShape?: (context: CanvasRenderingContext2D) => void
      onConfettiComplete?: (confettiInstance?: Confetti) => void
    }