Party.js: Confetti & Sparkle Effects in JavaScript

Category: Animation , Javascript , Recommended | November 5, 2026
AuthorYilianSource
Last UpdateNovember 5, 2026
LicenseMIT
Views26,315 views
Party.js: Confetti & Sparkle Effects in JavaScript

Party.js is a vanilla JavaScript library for creating confetti bursts, sparkles, and custom particle effects.

It renders particles on Canvas and launches effects from HTML elements or points on the page.

Features

  • Adjustable particle counts, colors, sizes, launch angles, and gravity.
  • Squares, circles, stars, text, images, paths, and custom particle shapes.
  • Custom effects with emission schedules, samplers, and behaviors.
  • Pause, resume, end, and stop controls for running effects.
  • Seeded randomness and reduced-motion preference handling.

How to Use Party.js

Installation

Load the browser bundle to use the global party object:

<script src="https://cdn.jsdelivr.net/npm/party-js@3/bundle/party.min.js"></script>

For ES modules, install the package and import the functions you need:

npm install party-js@3
import { confetti, sparkles, range } from "party-js";

Basic Confetti and Sparkles

Fire confetti and sparkles on button clicks with the browser bundle:

<button id="confetti-button">Confetti</button>
<button id="sparkles-button">Sparkles</button>
<script src="https://cdn.jsdelivr.net/npm/party-js@3/bundle/party.min.js"></script>
<script>
const confettiButton = document.querySelector("#confetti-button");
const sparklesButton = document.querySelector("#sparkles-button");
confettiButton.addEventListener("click", () => party.confetti(confettiButton));
sparklesButton.addEventListener("click", () => party.sparkles(sparklesButton));
</script>

Customize Confetti Colors and Shapes

Set the particle count, size, colors, and shapes in the button click handler:

import { confetti, range } from "party-js";
const button = document.querySelector("#confetti-button");
button.addEventListener("click", () => {
  confetti(button, {
    count: range(40, 60),
    spread: 70,
    size: range(6, 12),
    colors: ["#ff5a5f", "#ffb400", "#00a699"],
    shapes: [
      { type: "circle" },
      { type: "star", points: 5 },
      { type: "square", aspectRatio: 0.25, cornerRadius: 0.05 }
    ]
  });
});

Launch Confetti at the Pointer Position

Use the click event’s page coordinates to fire confetti at the pointer:

import { confetti } from "party-js";
document.addEventListener("click", (event) => {
  confetti({ x: event.pageX, y: event.pageY });
});

Add Image or Emoji Confetti

Use text or image shapes for custom particles. Replace /images/logo.png with your image URL, and preload it if it must appear in the first burst.

import { confetti, range } from "party-js";
const button = document.querySelector("#confetti-button");
button.addEventListener("click", () => {
  confetti(button, {
    shapes: [
      { type: "text", text: "🎉" },
      { type: "image", image: "/images/logo.png" }
    ],
    size: range(16, 28)
  });
});

Stop a Previous Confetti Burst

Keep the returned Effect handle to stop a previous burst before starting another.

import { confetti } from "party-js";
const button = document.querySelector("#confetti-button");
let activeEffect;
button.addEventListener("click", () => {
  activeEffect?.stop();
  activeEffect = confetti(button);
  activeEffect.finished.then((result) => console.log(result));
});

Create a Custom Particle Effect

Use createEffect() to control emission, particle initialization, and motion behaviors:

import {
  cone, createEffect, emitFrom, fade, gravity,
  measureTarget, pick, range
} from "party-js";
const button = document.querySelector("#confetti-button");
const { origin, area } = measureTarget(button);
const effect = createEffect({
  origin,
  schedule: { bursts: [{ count: 35 }] },
  particleInit: {
    position: emitFrom(area),
    velocity: cone(90, 40, range(200, 400)),
    size: range(8, 14),
    color: pick(["#ff5a5f", "#ffb400", "#00a699"]),
    shape: { type: "circle" },
    lifetime: range(1.5, 2.5)
  },
  behaviors: [gravity(500), fade(0, 0.5)]
});

Confetti Configuration

confetti(target, options?) emits a burst from an HTMLElement or a { x, y } point in page coordinates and returns an Effect handle.

OptionType, default, and behavior
countSampler<number>, default range(15, 30). Number of particles emitted in the initial burst; sampled once and rounded.
angleSampler<number>, default 90. Launch direction in degrees counter-clockwise from +x; 90 points up.
spreadSampler<number>, default 50. Angular deviation in degrees on either side of angle.
startVelocitySampler<number>, default range(800, 1500). Initial speed in pixels per second.
sizeSampler<number>, default range(6, 16). Initial particle size in pixels.
lifetimeSampler<number>, default range(2, 4). Particle lifetime in seconds.
colorsColor strings or a sampler; default randomHue({ l: 0.65, c: 0.15 }). An array is sampled per particle.
shapesShape objects or a sampler; defaults to [{ type: "circle" }, { type: "square", cornerRadius: 0.2 }, { type: "square", aspectRatio: 0.2, cornerRadius: 0.05 }].
gravitySampler<number>, default 800. Downward acceleration in pixels per second squared.
dragSampler<number>, default range(130, 220). Terminal falling speed in pixels per second.
reducedMotion"skip" | "play". Overrides the reduced-motion default for this effect; default behavior is "skip".
canvasHTMLCanvasElement, optional. Draws on a caller-supplied canvas.
seednumber, optional. Uses reproducible randomization; otherwise a random seed is generated.

Sparkles Configuration

sparkles(target, options?) emits four quick bursts of four-pointed stars from an element or page-coordinate point and returns an Effect.

OptionType, default, and behavior
countSampler<number>, default range(20, 40). Total sparkles across four bursts; sampled once.
startVelocitySampler<number>, default range(250, 480). Initial outward speed in pixels per second.
sizeSampler<number>, default 24. Maximum sparkle size in pixels; actual sizes vary.
lifetimeSampler<number>, default range(0.7, 1.4). Lifetime in seconds.
colorsArray of color strings or a sampler; default gradient(["oklch(0.7 0.15 70)", "oklch(0.95 0.15 70)"]).
reducedMotion"skip" | "play". Uses the global reduced-motion default unless overridden.
canvasHTMLCanvasElement, optional. Renders onto a caller-supplied canvas.
seednumber, optional. Reproducible randomness.

Effect Lifecycle API

MemberBehavior
stop()Removes all particles immediately. finished resolves with "stopped"; the effect cannot resume.
end()Stops subsequent emission and allows existing particles to expire naturally. finished resolves with "completed".
pause()Freezes active particles and the effect timeline.
resume()Continues a paused effect and skips the elapsed pause time.
finishedRead-only Promise<"completed" | "stopped">; resolves on effect completion or stopping and never rejects.

Custom Effect API

createEffect(options) starts a custom effect and returns an Effect.

CreateEffectOptions

OptionType and behavior
originRequired Live<Vec2>. Particle origin in page coordinates or custom-canvas coordinates; can be a function evaluated every frame.
scheduleRequired EmissionSchedule. Defines bursts, emission rate, duration, and looping.
particleInitRequired ParticleInit. Defines initial particle attributes.
behaviorsOptional Behavior[]. Applied in array order every simulation step.
lightOptional Live<Vec3>. Light direction; default { x: 0, y: 0, z: 1 }.
lightingOptional LightingFn | null; default createLighting(). Pass null to disable shading.
rngOptional Rng custom random generator. Takes precedence over seed.
reducedMotion"skip" | "play". Shared effect option.
canvasOptional HTMLCanvasElement. Shared effect option.
seedOptional number. Shared effect option.

EmissionSchedule and EmissionBurst

Custom schedules require at least one burst or a positive emission rate.

FieldType, default, and behavior
durationSeconds per loop; default 1. Must be positive and finite.
loopsNumber of loops; default 1. Use Infinity for an ongoing effect.
rateLive<number> particles per second; default 0. Can change during playback.
burstsEmissionBurst[]; default []. Each burst fires once per loop.
bursts[].timeSeconds from the start of a loop; default 0. Must fit within duration.
bursts[].countRequired Sampler<number>. Particle count, rounded when each burst fires.

ParticleInit and Particle

ParticleInit specifies each particle’s initial state. A running Particle has these fields plus age, the elapsed lifetime in seconds.

ParticleInit fieldMeaning
positionOptional Sampler<Vec3>. Initial position relative to the effect origin.
velocityOptional Sampler<Vec3>. Initial velocity.
orientationOptional Sampler<Quat>. Initial 3D rotation.
angularVelocityOptional Sampler<Vec3>. Angular speed in degrees per second.
sizeRequired Sampler<number>. Particle size in pixels.
colorRequired Sampler<string | Color>. Initial particle color.
shapeRequired Sampler<ParticleShape>. Drawing shape.
lifetimeRequired Sampler<number>. Particle lifetime in seconds.

Effect Utilities

FunctionParameters and result
measureTarget(target, canvas?)Returns { origin, area } for an element or page-coordinate point, optionally relative to a custom canvas.
emitFrom(shape)Samples positions inside a disk or rect emission shape.
createLighting(options?)Returns a LightingFn. ambient defaults to 0.5; peak defaults to 1.
setDefaultReducedMotion(mode)Sets the default reduced-motion policy to "skip" or "play" for effects started afterwards.
color(input)Parses a supported CSS color string into an Oklab Color object; also accepts an existing Color.

Emission Shapes

TypeFields
disk{ type: "disk", radius: number, center?: Vec2 }. Circular emission area.
rect{ type: "rect", width: number, height: number, center?: Vec2 }. Rectangular emission area.

Samplers and Randomization

Sampler<T> accepts a fixed value or a SamplerFn<T>. A sampler function receives SamplerContext: rng is the effect’s random generator, index identifies the sample, and optional batch contains a particle batch’s index and size.

FunctionParameters and result
range(min, max)Returns uniformly distributed numbers from min to max.
normal(mean, stdDev)Samples a normal distribution centered at mean; values are unbounded.
spread(center, deviation)Samples across evenly divided batch intervals around a center.
pick(values, weights?)Chooses one value from an array, optionally using weights.
gradient(colors)Samples interpolated colors from an array of strings/Color or GradientStop objects.
randomHue({ l, c, alpha? })Samples a hue with fixed Oklch lightness l and chroma c; alpha defaults to 1.
cone(angle, deviation, speed)Samples a 3D velocity vector over a cone of angles in degrees; speed accepts a sampler.
randomOrientation(axis?)Samples a rotation quaternion, optionally restricted to an axis.
randomSpin(min, max, axis?)Samples angular velocity in degrees per second; axis is optional.
evaluateSampler(sampler, ctx)Evaluates a sampler against its context, or returns a fixed value unchanged.

Particle Shapes

The ParticleShape union uses objects with a type field. All shapes use a unit-sized drawing area scaled by the particle’s pixel size.

Shape typeObject fields
circle{ type: "circle" }.
square{ type: "square", aspectRatio?: number, cornerRadius?: number }. Defaults: aspectRatio: 1, cornerRadius: 0.
star{ type: "star", points?: number, innerRadius?: number }. Defaults: points: 5, innerRadius: 0.382 (approximately).
polygon{ type: "polygon", sides: number }. Requires at least three sides.
path{ type: "path", path: Path2D }. Requires path coordinates normalized into the unit drawing area.
text{ type: "text", text: string, font?: string }. Default font: sans-serif.
image{ type: "image", image: string | CanvasImageSource }. Displays an image URL or loaded canvas-compatible image source.
custom{ type: "custom", draw: (ctx, particle) => void }. Custom Canvas drawing function.

Behaviors and Easing

Built-in behaviors and custom behavior functions operate on each particle during simulation.

FunctionBehavior
gravity(strength)Accelerates particles downward, in pixels per second squared.
drag(rate, edgeRatio?)Slows velocity at a per-second rate; edgeRatio defaults to 1 and can produce paper-like fluttering.
fade(inDuration, outDuration, ease?)Fades particle opacity over the specified durations in seconds at the start and end of its lifetime. Optional ease controls timing.
scale(inDuration, outDuration, ease?)Scales particle size over the specified durations in seconds at the start and end of its lifetime. Optional ease controls timing.
twinkle(options?)Adds intermittent glints. Defaults: glints: 1.5, length: 0.22 seconds, size: 0.25, brightness: 0.6.
linear()Returns constant-rate easing; used by default in fade() and scale().
sineIn()Returns a slow-start easing curve.
sineOut()Returns a slow-end easing curve.
sineInOut()Returns a slow-start and slow-end easing curve.

TypeScript Public Types

Exported type or classPurpose
BaseEffectOptionsShared reducedMotion, canvas, and seed configuration.
ConfettiOptions, SparklesOptionsOption contracts for the two built-in effects.
CreateEffectOptions, CreateLightingOptionsOptions for custom effects and lighting.
Effect, EffectResult, EffectTargetEffect handle, "completed" | "stopped" result, and HTMLElement | Vec2 target.
ReducedMotion, MeasuredTargetReduced-motion policy and { origin, area } result.
EmissionSchedule, EmissionBurst, EmissionShapeEmitter timing and emission area models.
DiskEmissionShape, RectEmissionShapeDisk and rectangular spawn region contracts.
Particle, ParticleInit, ParticleShapeParticle state, initial fields, and the union of shape objects.
CircleShape, SquareShape, StarShape, PolygonShapeBuilt-in geometric shape types.
PathShape, TextShape, ImageShape, CustomShapeCustom/path/text/image particle shape types.
Behavior, BehaviorObject, BehaviorInit, BehaviorUpdateParticle behavior function and object signatures.
BehaviorInitContext, BehaviorUpdateContextBehavior callback context; contains rng, and update context also contains dt (elapsed step in seconds).
Easing, LightingFn, LiveEasing: (t) => number; LightingFn: (color, coefficient) => Color; Live<T>: T | (() => T).
Sampler, SamplerFn, SamplerContextFixed/sampled values, sampler callbacks, and their random/batch context.
Color, GradientStop, RandomHueOptionsColor has numeric l, a, b, alpha; GradientStop has offset (0 to 1) and color; RandomHueOptions has l, c, and optional alpha.
Vec2, Vec3, QuatVec2 has x, y; Vec3 has x, y, z; Quat has x, y, z, w.
RngRandom number callback returning a value from 0 inclusive to 1 exclusive.
TwinkleOptionsglints, length, size, and brightness.
PartyJSErrorExported error class for invalid configuration and browser-only execution errors.

Migrating from Party.js v2

v2v3 equivalent
import party from "party-js"import { confetti, sparkles, range } from "party-js". Use import * as party if you want a namespace.
party.variation.range(20, 40)range(20, 40) in modules or party.range(20, 40) in the browser bundle.
party.settings.gravityUse the per-effect gravity option or the gravity() behavior.
party.settings.debug / zIndexRemoved. Pass your own canvas to control the drawing surface.
"roundedRectangle" / "roundedSquare"Shape objects with type: "square" plus cornerRadius and optional aspectRatio.
party.resolvableShapesUse image, text, path, or custom shape objects.
party.variation.skew(value, amount)range(value - amount, value + amount).
party.variation.skewRelative(value, percentage)range(value * (1 - percentage), value * (1 + percentage)).
party.variation.splineSample(spline)Removed; create a custom sampler when spline-based sampling is required.
party.variation.gradientSamplegradient(colors).
party.scene / ModuleBuilderUse createEffect() and behaviors.
size: 1Sizes are now in pixels; v2 used relative shape scaling.

Alternatives and Related Resources

Changelog:

v3.0.0 (07/11/2022)

  • New Canvas particle engine, updated confetti and sparkle effects, simplified public API, new samplers and behaviors.

v2.2.0 (07/11/2022)

  • add shape support to sparkles template

v2.1.3 (06/08/2022)

  • remove source maps

v2.1.2 (10/12/2021)

  • fixed the previous patch files
  • added prepublish hook

v2.1.0 (10/09/2021)

  • expose sparkle lifetime, organize imports

v2.1.0 (09/26/2021)

  • fix container size
  • removed stale
  • upgrade security packages
  • Feature/reduced motion
  • fix container size, added dev server
  • chore: update typedoc-plugin-markdown to 3.10.1
  • Improve library exports
  • Added generated API

v2.0.1 (09/25/2021)

  • fix container size

v2.0.0 (05/13/2021)

  • Feature/better emission

v2.0.0 (05/10/2021)

  • improvements

v2.0.0 (04/19/2021)

  • Rewritten
  • Doc & Demo update

v1.0.4 (01/12/2021)

  • Update party.js to keep the rendering always on top
  • Add an init function

v1.0.3 (01/03/2021)

  • Fixed references

v1.0.2 (01/02/2021)

  • Added proper AMD/CJS/Browser loading support

11/05/2020

  • v1.0.1

11/03/2020

  • Added default shapes

10/30/2020

  • Added color class & gradient

10/28/2020

  • Added randomization function

You Might Be Interested In:


Leave a Reply