This is the full developer documentation for party.js
# Introduction
> What party.js is, what it can do, and where to start.
party.js adds particle effects to your website, to brighten up your users’ browsing experience: confetti when someone completes a form, sparkles when they unlock something, or anything else you can build out of particles. A single function call is enough to get you started:
```js
import { confetti } from "party-js";
button.addEventListener("click", () => confetti(button));
```
## What you get
* **Ready-to-go effects.** [Confetti](/effects/confetti/) and [sparkles](/effects/sparkles/) work without any configuration. For smaller customizations, you can easily override their default options.
* **The engine behind them.** The built-in effects use the same public API you have access to. If they aren’t enough, [`createEffect()`](/api/custom_effects/createeffect/) lets you build your own effects!
* **Small and dependency-free.** Under 12 KB minified and gzipped. Tree-shakeable, so bundlers only include what you import.
* **Typed.** Written in TypeScript, with full type definitions.
* **Safe to import anywhere.** Importing the library during server-side rendering works. Effects themselves only run in the browser.
* **Respects reduced motion.** Effects are skipped by default when the user asks their system for less motion.
## How it works
Every effect is made of particles: small shapes like squares, circles or stars, each with its own position, velocity, rotation, size, color and lifetime. Three things decide what they do:
* An **emitter** decides when particles are created and where they start.
* **Samplers** pick the starting values for each particle, such as a random speed or a color from a list or gradient.
* **Behaviors** change particles while they’re alive, for example gravity pulling them down or a fade at the end of their lifetime.
party.js simulates the particles at a fixed rate, draws them onto a canvas on top of your page, and removes the canvas again once the last particle is gone.
You don’t need any of this to fire confetti, but it’s the vocabulary the rest of the docs use. [How an effect works](/concepts/effects/) goes into more detail.
## Browser support
party.js works in all current browsers. It draws with the Canvas 2D API and is published as ES2022. If you need to support older browsers, have your bundler transpile it.
## Where to go next
* [Installation](/installation/) shows how to add party.js to your project, with a package manager or a script tag.
* [Quickstart](/quickstart/) walks you through your first effect and how to customize it.
* Coming from party.js v2? [Migrating from v2](/migrating-from-v2/) lists what changed.
Once you’re set up, [Effects](/effects/confetti/) describes each built-in effect, [Guides](/guides/custom-effects/) show how to build your own, and the [API reference](/api/) lists everything the library exports.
# Installation
> How to add party.js to your project.
party.js is published on npm as `party-js`. It has no dependencies and ships with TypeScript types.
Using an AI assistant?
Give it [`llms-full.txt`](https://party.js.org/llms-full.txt), the complete v3 docs in one file, to ensure it does not write v2 code by accident.
## With a package manager
* npm
```sh
npm install party-js
```
* pnpm
```sh
pnpm add party-js
```
* yarn
```sh
yarn add party-js
```
* bun
```sh
bun add party-js
```
Then import what you need:
```js
import { confetti } from "party-js";
```
party.js is an ES module without side effects, so bundlers only include the parts you import.
## With a script tag
Without a build step, you can load the bundle from a CDN. It puts everything on a global `party` object:
```html
```
If you prefer modules, import it directly instead:
```html
```
`@3` always loads the latest 3.x release. In production, pin an exact version such as `@3.0.0`, so an update can’t change your site without you noticing.
## With a framework
party.js doesn’t need a wrapper for React, Vue or Svelte: get the element and call the effect. Effects need a browser, so start them from event handlers or after the component has mounted, never during rendering. Importing party.js on the server is fine though.
* React
```jsx
import { confetti } from "party-js";
export function SubmitButton() {
return ;
}
```
* Vue
```vue
```
* Svelte
```svelte
```
# Quickstart
> Fire your first effect and customize it.
This page assumes you’ve [installed](/installation/) party.js. It takes you from a first burst of confetti to customizing and controlling effects.
## Your first effect
Pass an element to `confetti()`, and confetti bursts out of it:
```js
import { confetti } from "party-js";
const button = document.querySelector("#submit");
button.addEventListener("click", () => confetti(button));
```
The confetti shoots out of the middle of the element, slows down quickly, and then flutters down like paper. The library draws it on a canvas over the page and removes the canvas again once the last piece is gone.
## Customizing
Every effect takes an options object as its second argument. Options you leave out keep their default:
```js
import { confetti, range } from "party-js";
confetti(button, {
count: range(60, 90),
spread: 100,
startVelocity: range(1200, 2000),
});
```
Most options accept either a fixed value, like `spread: 120`, or a [sampler](/concepts/samplers/), like `range(80, 120)`, which picks a new random value each time it’s used. That’s what makes every burst look unique. Each option’s documentation says whether it’s picked once per burst or once per piece of confetti.
Colors work the same way. Pass a list of color strings and each piece picks one of them:
```js
confetti(button, {
colors: ["#ff5a5f", "#ffb400", "#00a699", "#7b61ff"],
});
```
Visit [Confetti](/effects/confetti/) for more information on the effect.
## Fire from a point
Instead of an element, you can pass a position in page coordinates, i.e. pixels from the top-left of the document. For example, to fire confetti wherever the user clicks:
```js
area.addEventListener("click", (event) => {
confetti({ x: event.pageX, y: event.pageY });
});
```
## Sparkles
The other built-in effect is `sparkles()`. It works just like `confetti()`: it takes an element or a point, and an options object. Instead of confetti, it bursts small golden sparkles out in all directions, which twinkle and glint.
```js
import { sparkles } from "party-js";
sparkles(button);
```
Visit [Sparkles](/effects/sparkles/) for more information on the effect.
## Control a running effect
Effects start right away and clean up after themselves, so most of the time you can ignore what they return. When you need control, keep the returned effect:
```js
const effect = confetti(button);
effect.pause(); // freezes the particles where they are
effect.resume(); // continues where it left off
effect.end(); // stops emitting, and lets the particles that are alive finish
effect.stop(); // removes the particles immediately
effect.finished; // a promise that resolves once the effect has ended
```
`stop()` is useful when the element the confetti belongs to goes away, for example when your component unmounts. `end()` matters for effects that emit particles continuously, like a [custom](/guides/custom-effects/#from-bursts-to-streams) stream: it turns them off gracefully, instead of making their particles vanish instantly.
## Reduced motion
When a user has asked their system for reduced motion, party.js skips effects by default: nothing is drawn, and your code keeps running as if the effect had played. If your particles carry information the user shouldn’t miss, or the user explicitly asked for them, you can play them anyway:
```js
confetti(button, { reducedMotion: "play" });
```
To change the default behavior for every effect, for example from a motion setting on your site, use [`setDefaultReducedMotion()`](/api/effects/setdefaultreducedmotion/).
## Next steps
* [Effects](/effects/confetti/) describes each built-in effect and all its options.
* [Samplers & randomness](/concepts/samplers/) explains how values are picked, and which samplers there are.
* [Custom effects](/guides/custom-effects/) shows how to build your own effect when the built-in ones aren’t enough.
# Confetti
> Paper-like confetti that bursts in an upwards cone.
```js
import { confetti } from "party-js";
confetti(button);
```
[PlaygroundsTry it in the effects playground](/playgrounds/effects/?effect=confetti)
## Usage
Pass the element the confetti should come from. The confetti shoots out of the middle of the element, fast and mostly along its `angle`. Drag slows it down within a fraction of a second, and it then flutters down slowly like paper, swaying as it tumbles.
```js
import { confetti, range } from "party-js";
button.addEventListener("click", () => {
confetti(button, {
count: range(40, 60),
spread: 70,
});
});
```
You can find a complete list of options and their defaults in the [reference](/api/effects/confettioptions/).
# Sparkles
> Golden sparkles that burst outwards and glint.
```js
import { sparkles } from "party-js";
sparkles(button);
```
[PlaygroundsTry it in the effects playground](/playgrounds/effects/?effect=sparkles)
## Usage
Pass the element the sparkles should burst out of. They appear in four quick bursts from the middle of the element, shoot outwards, and then hover for a moment while they settle. Occasionally, a sparkle briefly grows and flashes towards white.
Most sparkles are small, with a few big ones among them. The `size` option sets the size of the largest ones:
```js
import { range, sparkles } from "party-js";
button.addEventListener("click", () => {
sparkles(button, {
count: range(40, 60),
size: 16,
});
});
```
The glints come from the [`twinkle()`](/api/behaviors/twinkle/) behavior, which you can use in your [own effects](/guides/custom-effects/) too.
You can find a complete list of options and their defaults in the [reference](/api/effects/sparklesoptions/).
# Behaviors
> How particles change while they're alive.
Even though a particle’s properties can start out randomized, effects would look quite plain if the particles do not change over time. For example, confetti shoots up, slows down, falls and fades away, and none of that is decided when it spawns. It’s the work of **behaviors**, small functions that change a particle throughout the simulation. This page explains when behaviors run, what the built-in ones do and why their order matters.
## What a behavior is
A [`Behavior`](/api/behaviors/behavior/) is a function that receives a particle and changes it, on every simulation step. It can also be an object with an extra `init` function, which runs once when a particle spawns, for example to remember its starting size. [Custom behaviors](#custom-behaviors) shows how to write your own.
A custom effect lists its behaviors in `behaviors`, and they apply to all of its particles:
```js
import { createEffect, drag, fade, gravity, scale } from "party-js";
createEffect({
// ...
behaviors: [gravity(800), drag(5), scale(0.2, 0), fade(0, 1)],
});
```
Functions like `gravity()` don’t change anything themselves. Instead they return the behavior, which is then called during the simulation loop.
The built-in effects use the same behaviors. [`confetti()`](/api/effects/confetti/) applies downwards force with `gravity()`, slows them with `drag()`, grows them in with `scale()` and fades them out with `fade()`. Their impact on the particles can be tuned via their parameters. Built-in effects commonly expose those parameters as options, for example [ConfettiOptions.gravity](/api/effects/confettioptions/#gravity).
Note
Built-in effects do not accept behaviors of their own, to avoid behaviors unexpectedly interfering with each other. To add behaviors, build the effect with [`createEffect()`](/api/custom_effects/createeffect/) instead.
## When behaviors run
A behavior can do work at two moments in a particle’s lifecycle:
* **When the particle spawns**, right after its values have been sampled. A behavior can prepare the particle here, for example by remembering its starting size. This is optional.
* **On every simulation step** while the particle is alive, which is where the actual modification happens.
Each step, party.js first ages the particle, then runs the behaviors on it, in the order they’re listed in, and lastly applies the physics simulation. [Effects](/concepts/effects/#the-life-of-a-particle) covers this in more detail.
Behaviors don’t run on dead particles. Once a particle’s `age` reaches its `lifetime`, it’s removed at the end of the step, without another update.
## Built-in behaviors
| Behavior | Description |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| [`gravity(strength)`](/api/behaviors/gravity/) | Pulls particles down with constant acceleration. |
| [`drag(rate, edgeRatio?)`](/api/behaviors/drag/) | Slows particles down in proportion to their speed, and optionally makes them flutter like paper. |
| [`fade(in, out, ease?)`](/api/behaviors/fade/) | Fades particles in after they spawn, and out before they die. |
| [`scale(in, out, ease?)`](/api/behaviors/scale/) | Grows particles from nothing after they spawn, and shrinks them away before they die. |
| [`twinkle(options?)`](/api/behaviors/twinkle/) | Makes particles glint occasionally, growing a little and flashing towards white. |
### Gravity and drag
`gravity()` and `drag()` affect a particle’s velocity. Like positions and velocities, they work in pixels and seconds, in particle space, where +y points up.
`gravity(strength)` adds `strength` pixels per second to the particle’s downward speed, every second. Confetti uses 800 by default. A negative strength pulls particles up instead, for example to make bubbles rise.
`drag(rate)` works against the particle’s movement, in every direction. Every second, the particle loses the fraction `rate` of its velocity, so drag is strongest while a particle is fast: a burst slows down sharply at first, then more and more gently. That’s how a burst of confetti can shoot out fast and still come to a stop within a few hundred pixels.
Together, the two make a falling particle speed up until it reaches a steady speed, its **terminal velocity**, of `strength / rate`. If you know how fast particles should fall at most, you can calculate the rate from it, just like `confetti()` does behind the scenes:
```js
const g = 800; // px/s²
const terminalVelocity = 160; // px/s
const behaviors = [gravity(g), drag(g / terminalVelocity)];
```
Tip
Since the same rate decides both, particles that fall slowly also don’t fly as far. To keep a slow fall and still cover more distance, launch the particles faster.
The rate is measured in 1/s, and sensible values usually lie between 2 and 10. It’s [sampled](/concepts/samplers/) once for each particle, so you can also pass something like `drag(range(4, 6))`. The particles then fall at slightly different speeds, and a cloud of them stretches out as it falls, instead of coming down as a block.
#### Fluttering
A piece of paper doesn’t fall straight down. It meets more resistance when it moves face-on than when it moves edge-on, so while it’s tilted, part of its fall turns into a sideways glide. As it tumbles, the tilt flips and the glide changes direction, and the paper sways from side to side.
The optional second argument of `drag()`, `edgeRatio`, simulates this. It sets how much drag a particle feels when it moves edge-on, relative to when it moves face-on:
```js
const behaviors = [gravity(800), drag(800 / 160, 0.4)];
```
With the default of 1, drag is the same in every direction. Values between 0.3 and 0.5 give a paper-like flutter, which is what `confetti()` uses, and lower values make particles glide far to the side. The face is the plane of the particle’s shape, so fluttering needs particles that tumble, for example with [`randomSpin()`](/api/samplers/randomspin/).
### Fading and scaling
`fade()` and `scale()` affect the start and the end of a particle’s life. Both take two durations, in seconds:
* During the first `in` seconds after spawning, the particle fades in from transparent, or grows from a size of 0.
* During the last `out` seconds before dying, it fades out again, or shrinks back to 0.
Pass 0 to skip either half. `fade(0, 1)` fades particles out over the last second of their life, and `scale(0.2, 0)` grows them in over the first 0.2 seconds.
If both durations together are longer than a particle’s lifetime, the transitions overlap, and it never reaches its full opacity or size.
Both behaviors work relative to the particle’s starting value. `scale()` grows it to the size it was sampled with, and `fade()` multiplies the opacity of its color, so a color that starts half transparent fades in to half transparent, not to fully opaque.
#### Easing
By default, fading and scaling progress at a constant rate. Pass an [`Easing`](/api/behaviors/easing/) as the third argument to make them start or end softly instead:
| Easing | Description |
| ------------------------------------------ | ----------------------------------------------- |
| [`linear()`](/api/behaviors/linear/) | At a constant rate. The default. |
| [`sineIn()`](/api/behaviors/sinein/) | Starts slowly, and speeds up. |
| [`sineOut()`](/api/behaviors/sineout/) | Starts quickly, and slows down. |
| [`sineInOut()`](/api/behaviors/sineinout/) | Starts slowly, speeds up, and slows down again. |
The out-transition runs the same curve backwards. An easing that starts the fade-in softly, like `sineIn()`, also makes the fade-out end softly.
An easing is just a function that turns a progress from 0 to 1 into the eased value, which should also go from 0 to 1, meaning you can easily write your own:
```js
const cubicIn = (t) => t ** 3;
fade(0.2, 0.5, cubicIn);
```
### Twinkling
`twinkle()` makes particles glint occasionally: for a short moment, a particle grows a little and its color flashes towards white, then it settles back to how it was. Each particle glints a few times during its life, at random moments, so a group of them seems to sparkle. That’s what gives [`sparkles()`](/effects/sparkles/) its shimmer.
```js
twinkle({ glints: 1.5, length: 0.22, size: 0.25, brightness: 0.6 });
```
`glints` sets how many glints a particle catches per second, on average, and `length` how long each one lasts, in seconds. `size` is how much the particle grows at the peak of a glint, so `0.25` makes it 25% larger, and `brightness` how far its color moves towards white, from 0 to 1. The values above are the defaults, so `twinkle()` on its own looks the same.
The glint is applied on top of the particle’s size and color. Since `scale()` sets the size from scratch on every step, list `twinkle()` after it, as explained [below](#the-order-of-behaviors).
## The order of behaviors
Behaviors run in the order they’re listed in, and each one sees the changes of the ones before it. Whether that matters depends on how a behavior changes a value:
* Some behaviors **change** a value step by step. `gravity()` and `drag()` adjust the velocity the particle already has, so their changes build up over time.
* Others **set** a value from scratch on every step. `scale()` calculates the size from the starting size and the particle’s age, and `fade()` does the same for the opacity. Whatever happened to the value before is overwritten.
For behaviors of the first kind, the order barely matters. Behaviors of the second kind replace the changes of everything listed before them. For example, here is a behavior that makes particles pulse:
```js
import { createEffect, scale } from "party-js";
const pulse = (particle) => {
particle.size *= 1 + 0.3 * Math.sin(particle.age * 10);
};
createEffect({
// ...
behaviors: [scale(0.2, 0.5), pulse],
});
```
Listed after `scale()`, `pulse` changes the freshly calculated size on every step, and the particles pulse while they grow and shrink. Listed before it, its change would be overwritten right away, and nothing would pulse. And on its own, without `scale()` resetting the size on every step, it would multiply the size it changed the step before, and the particles would quickly grow or shrink out of control.
## Custom behaviors
The simplest behavior is a function. party.js calls it for every particle, on every simulation step, with the particle and a [context](/api/behaviors/behaviorupdatecontext/). Here’s one that pushes particles to the right, like a steady breeze:
```js
const breeze = (particle, ctx) => {
particle.velocity = {
...particle.velocity,
x: particle.velocity.x + 100 * ctx.dt,
};
};
```
`ctx.dt` is the length of the step, in seconds. Anything that’s meant to happen *per second* should be multiplied by it to keep effects framerate-independent. Here, the breeze adds 100 pixels per second to the speed, every second. Without `dt`, it would add 100 on every step, 120 times a second.
The new velocity is a new object, built from the old one, which keeps your behavior from accidentally changing a value that’s shared with something else.
Tip
When using TypeScript, give the function the [`Behavior`](/api/behaviors/behavior/) type, and the particle and context are typed for you.
### Taking options
To make the strength adjustable, wrap the behavior in a function that takes the options, and returns the behavior. All built-in behaviors are written this way.
```js
import { createEffect, drag, fade, gravity, scale } from "party-js";
const breeze = (strength) => (particle, ctx) => {
particle.velocity = {
...particle.velocity,
x: particle.velocity.x + strength * ctx.dt,
};
};
createEffect({
// ...
behaviors: [gravity(-300), drag(1.7), breeze(100), scale(0.3, 0), fade(0, 1)],
});
```
### Storing data per particle
A breeze pushes every bubble the same way. To make them sway from side to side instead, each bubble can follow a wave over time, `Math.cos(particle.age * 3)`. But then all bubbles would sway in sync, which would look too stiff. To solve this, we assign each bubble a random **phase** when it spawns, which it can store and access later on.
For that, a behavior can be an object instead of a function. Its `init` function runs once for each particle, right after it spawns, and its `update` function runs on every step, like a plain behavior function would. We can use a `WeakMap` to store per-particle data in the behavior:
```js
import { createEffect, drag, fade, gravity, scale } from "party-js";
// pushes each particle from side to side, starting at a random point of the swing
const sway = (strength) => {
const phaseMap = new WeakMap();
return {
init(particle, ctx) {
phaseMap.set(particle, ctx.rng() * 2 * Math.PI);
},
update(particle, ctx) {
const offset = phaseMap.get(particle);
const push = Math.cos(particle.age * 3 + offset) * strength * ctx.dt;
particle.velocity = {
...particle.velocity,
x: particle.velocity.x + push,
};
},
};
};
createEffect({
// ...
behaviors: [gravity(-300), drag(1.7), sway(200), scale(0.3, 0), fade(0, 1)],
});
```
A couple of notes on the implementation:
* **The lookup is a `WeakMap`**, created inside the outer function. Every call of `sway()` creates a new one, so two sways in the same effect never overwrite each other’s values. Also, a particle’s entry is cleaned up along with the particle after it has expired.
* **The phase comes from `ctx.rng`**, the effect’s random number generator, and not from `Math.random()`, to keep the effect [reproducible](/concepts/samplers/#reproducible-randomness).
### Quadratic drag
As a last example, here’s quadratic drag, where air resistance grows with the square of the speed, as it does for real objects. The built-in `drag()` is linear instead, so that a slow fall doesn’t force a short flight:
```js
const quadraticDrag = (coefficient) => (particle, ctx) => {
const { x, y, z } = particle.velocity;
const factor = 1 / (1 + coefficient * Math.hypot(x, y, z) * ctx.dt);
particle.velocity = { x: x * factor, y: y * factor, z: z * factor };
};
```
Dividing by `1 + ...` instead of subtracting keeps a fast particle from overshooting and reversing direction in a single step. Together with gravity, the terminal velocity is `Math.sqrt(strength / coefficient)`, so to fall at most `v` pixels per second, use `quadraticDrag(strength / v ** 2)`. The coefficient is measured in 1/px, so sensible values are tiny, usually between 0.0005 and 0.02.
### Things to keep in mind
* **Keep updates cheap.** An update runs for every particle, 120 times a second. Don’t read from the page in it, for example with `getBoundingClientRect()`. Ideally you would measure once, in the outer function, and use the result.
* **Errors stop the effect.** If a behavior throws, the effect is stopped right away, and its [`finished`](/api/effects/effect/) promise resolves with `"stopped"`. The error is reported in the console, and other effects keep running.
# Colors & lighting
> How particles are colored and lit.
Wherever party.js takes a color, you can pass a CSS color string:
* hex colors, like `#ff5a5f`, `#f00` or `#ff000080`,
* the `rgb()`, `hsl()`, `oklab()` and `oklch()` functions, like `rgb(255 90 95)` or `oklch(0.7 0.15 20)`.
Named colors like `red` or `transparent` aren’t supported, to save on bundle size.
Strings are converted with [`color()`](/api/utilities/color/), which you can also call yourself. It returns a [`Color`](/api/utilities/color-type/), an object in the **Oklab** color space. Oklab is designed to match how we perceive colors: equal steps in it look like equal steps to the eye. That’s why party.js uses it internally. Colors blend smoothly, without muddy or overly bright spots in between, and [lighting](#lighting) can make a color darker or brighter without changing its hue.
```js
import { color } from "party-js";
color("#ff5a5f"); // { l: 0.69, a: 0.19, b: 0.08, alpha: 1 }, rounded
```
A `Color` has a lightness `l`, from 0 (black) to 1 (white), two coordinates `a` and `b` that describe its hue and how intense it is, and an `alpha` for its opacity. You’ll rarely need to touch them directly, except when you change a particle’s color in a [custom behavior](/concepts/behaviors/#custom-behaviors).
## Picking colors
Colors work like any other [sampled value](/concepts/samplers/). The built-in effects take a list of colors and pick one for each particle, and three samplers give you more control:
* [`pick(colors, weights?)`](/api/samplers/pick/) picks one of the given colors, optionally with weighted chances.
* [`gradient(colors)`](/api/samplers/gradient/) picks a random color along a gradient, including the colors in between.
* [`randomHue({ l, c })`](/api/samplers/randomhue/) picks a color with a random hue, but a fixed lightness `l` and intensity (chroma) `c`.
A gradient blends its colors in Oklch, the polar form of Oklab, which goes around the color wheel. Between two colors, it passes through the hues in between, instead of a dull gray:
```js
import { confetti, gradient } from "party-js";
confetti(button, {
colors: gradient(["#7b61ff", "#ff5a5f", "#ffb400"]),
});
```
The colors of a gradient are spaced evenly by default. To make some of them more common, place them yourself with **stops**. A wider gap between two stops means more particles get a color from that part of the gradient:
```js
// mostly pinks, with a short blend into gold at the end
gradient([
{ offset: 0, color: "#ff5a5f" },
{ offset: 0.8, color: "#ff8fa3" },
{ offset: 1, color: "#ffb400" },
]);
```
`randomHue()` makes the most of Oklab: since all of its colors share the same lightness, none of them stands out, which is hard to get right with `hsl()`. Lightnesses from 0.6 to 0.8, and chromas from 0.1 to 0.2 give vivid, even mixes. Much higher chromas go beyond what a screen can show, and get clipped, which can shift their hue a little.
## Lighting
A turning piece of paper is brightest when it faces the light, and darker when it’s tilted away. party.js imitates this by adjusting the color of each particle on every frame, depending on how directly its face points towards the light.
How strongly a particle faces the light is a number from -1 to 1, the **lighting coefficient**. It’s 1 when the front of the particle faces the light directly, 0 when the light hits it edge-on, and -1 when its back faces the light. An effect’s `lighting` option turns this number into a color.
By default, effects use [`createLighting()`](/api/custom_effects/createlighting/). It multiplies the particle’s lightness by a factor between `ambient`, for particles hit edge-on, and `peak`, for particles facing the light, from either side. With the default values of 0.5 and 1, a particle facing the light is drawn in its own color, and one seen edge-on at half its lightness.
A `peak` above 1 makes particles brighter than their own color when they face the light, which makes them flash as they turn. Confetti uses a `peak` of 1.5.
```js
import { createEffect, createLighting } from "party-js";
createEffect({
// ...
lighting: createLighting({ ambient: 0.2, peak: 1.5 }),
});
```
Since lighting only changes the lightness, and party.js stores colors in the Oklab color space, a lit particle keeps its hue. A red piece of confetti gets darker or brighter, but never turns brown or pink.
Tip
You can pass `lighting: null` to turn lighting off, and draw particles in exactly their own color.
### The light’s direction
By default, the light comes from the front, from where the viewer is. The `light` option changes its direction, as a vector in particle space, where +x points right, +y up and +z towards the viewer. Its length doesn’t matter:
```js
createEffect({
// ...
light: { x: -1, y: 1, z: 1 }, // from the top left, in front of the canvas
});
```
The direction is a [live value](/api/custom_effects/live/), so it’s read again on every frame. Pass a function, and the light can move while the effect runs, for example to follow the cursor.
### Custom lighting
The `lighting` option takes any function that receives the particle’s color and its lighting coefficient, and returns the color to draw:
```js
import { createEffect } from "party-js";
// darker at an angle, with a white flash when facing the light directly
const glint = (color, coefficient) => {
const facing = Math.abs(coefficient);
const shine = facing ** 16; // close to 0, unless facing the light
return {
...color,
l: color.l * (0.5 + 0.5 * facing) + (1 - color.l) * shine,
};
};
createEffect({
// ...
lighting: glint,
});
```
`glint` darkens particles that are tilted away, like the default lighting, but makes particles that face the light almost directly flash white. Raising the coefficient to a high power keeps the flash short: 0.9 to the power of 16 is less than 0.2.
The coefficient tells the front and the back of a particle apart, so your function can treat them differently. The default lighting ignores the sign, since paper looks the same from both sides, but a material with a different back side could darken it, or give it a different color altogether.
Two things to keep in mind:
* **Return a new color.** The color your function receives belongs to the particle. Changing it would change the particle itself, and the lighting would apply again on the next frame.
* **Keep it quick.** The function runs for every particle on every frame.
# How effects work
> What happens in between calling an effect and the last particle disappearing.
Even though calling `confetti(button)` takes only a single line, a lot happens until the last piece disappears. Particles are spawned, moved, drawn and removed again, many times per second. This page explains the internal lifecycle of an effect. You don’t need any of it to use the built-in effects, but it helps when you customize them, or [build your own](/guides/custom-effects/).
## Anatomy of an effect
Every effect, including the built-in ones, is created with [`createEffect()`](/api/custom_effects/createeffect/). Four options describe it:
* **`origin`** is the point that defines the center of the coordinate system of the effect. Particle positions are measured from it.
* **`schedule`** decides when particles are emitted, and how many.
* **`particleInit`** describes how each new particle starts out: where, how fast, in which color and shape, and for how long it lives.
* **`behaviors`** change particles while they’re alive, for example gravity pulling them down, or fading them out at the end.
Here is an example of an effect that uses all four:
```js
import { cone, createEffect, emitFrom, fade, gravity, measureTarget, pick, randomOrientation, randomSpin, range } from "party-js";
const { origin, area } = measureTarget(button);
createEffect({
origin,
schedule: { bursts: [{ count: 30 }] },
particleInit: {
position: emitFrom(area),
velocity: cone(90, 30, range(200, 400)),
orientation: randomOrientation(),
angularVelocity: randomSpin(90, 270),
size: range(8, 14),
color: pick(["#ff5a5f", "#ffb400", "#00a699"]),
shape: { type: "circle" },
lifetime: range(1, 2),
},
behaviors: [gravity(800), fade(0, 0.5)],
});
```
A few more options control where the effect is drawn and how it’s lit, which this page covers further down.
## The schedule
The [schedule](/api/custom_effects/emissionschedule/) decides when particles are emitted. It runs for `duration` seconds (1 by default), and repeats that `loops` times (once by default). During each loop, particles can be emitted in two ways:
* **Bursts** emit a group of particles all at once, at a set `time` within the loop.
* A **rate** emits particles continuously, a number of them per second.
```js
// a single burst of 40 particles, like confetti
const single = { bursts: [{ count: 40 }] };
// two bursts, half a second apart
const double = { bursts: [{ count: 30 }, { time: 0.5, count: 30 }] };
// a steady stream of 20 particles per second, for three seconds
const stream = { duration: 3, rate: 20 };
// a stream that runs until the effect is ended or stopped
const endless = { loops: Infinity, rate: 20 };
```
A burst’s `count` can be a [sampler](/concepts/samplers/), which is sampled each time the burst fires. The `rate` can be a [live value](/api/custom_effects/live/) instead, which is read again on every simulation step, so a stream can speed up, slow down, or depend on the size of the window. While it’s 0, the stream pauses, and when it rises again, the stream picks up at that pace, without making up for the particles it skipped.
```js
// emit between 20 and 40 particles each burst
const rangeBurst = { bursts: [{ count: range(20, 40) }] };
// emit more particles the wider the window is
const windowDependent = { rate: () => window.innerWidth / 100 };
```
A schedule that never emits anything, because it has no bursts and a rate of 0, throws an error when the effect is created. The same goes for a burst whose `time` lies outside the loop’s `duration`, since it would never fire.
## Spawning: when a particle is born
Each time the schedule emits particles, they’re created (“spawned”) one after another. For every new particle, each field of `particleInit` is read once, and the results become the particle’s initial state.
Positions and velocities are in **particle space**: pixels relative to the origin, with +x pointing right and +y pointing **up**. That’s the opposite of the page, where +y points down. Particles also have a z coordinate, which lets them rotate in 3D, but it doesn’t change where they’re drawn.
Particles that spawn in the same simulation step, such as all particles of a burst, form a [batch](/concepts/samplers/#batches). Samplers can use this to spread the particles of a burst evenly, as for example the sparkles do.
Right after a particle’s values are sampled, each [behavior](/concepts/behaviors/) that has an `init` function is called, for example to remember the particle’s starting size.
Note
Values that are fixed rather than sampled are checked once, when the effect is created, so a typo in a shape or color throws right away. A value that comes from a sampler can only be checked when it’s produced, so its mistakes throw when a particle spawns.
## The life of a particle
Every [particle](/api/particles/particle/) has a position, velocity, orientation, angular velocity, size, color, shape, an `age` and a `lifetime`. On each simulation step, party.js does three things to every particle, in this order:
1. It ages the particle by the length of the step. Once `age` reaches `lifetime`, the particle is considered dead and skips the rest.
2. It runs the effect’s behaviors on it, in the order they’re listed in. They can change anything about the particle, most commonly its velocity, size or color.
3. It moves the particle by its velocity, and rotates it by its angular velocity.
Dead particles are removed at the end of the step. A particle can’t be revived, and it doesn’t get a final update after its last step.
Because behaviors run before the movement, a behavior that changes the velocity takes effect in the very same step. And because they run in order, the order can matter when one behavior reads a value that another one changes. [Built-in behaviors](/concepts/behaviors/#built-in-behaviors) explains the built-in behaviors, and [Custom behaviors](/concepts/behaviors/#custom-behaviors) how to write your own.
## Time and the simulation loop
The logic for simulating particles and drawing them is kept separate. The simulation always advances in fixed steps of 1/120 of a second, no matter how fast the screen refreshes. On every animation frame, it runs as many steps as fit into the time that has passed since the last frame, and then draws the particles once. This keeps effects framerate-independent and allows [seeded effects](/concepts/samplers/#reproducible-randomness) to look identical, even on monitors with different refresh rates.
Animation frames don’t always arrive on time: a busy page can hang for a moment, and browsers stop animating tabs that are in the background. If a frame arrives so late that it would need more than 8 steps, only those 8 steps are run and the rest of the time is skipped. This prevents the effect from jumping ahead or freezing the page while it catches up.
[Pausing](/api/effects/effect/#pause) works the same way: a paused effect is still drawn, but no simulation steps are run, and the time spent paused is skipped once it resumes.
## The canvas
Particles are drawn onto a canvas. Unless you pass your own, party.js uses one fullscreen canvas that all running effects share. It’s created when the first effect starts, and removed once the last one ends, so it only exists while there’s something to draw.
The canvas sits on top of the page without getting in the way: it doesn’t react to the mouse, isn’t announced to screen readers, and is shown above other content, including dialogs and fullscreen elements. It follows the size of the window, and is drawn at the screen’s pixel density, so particles stay sharp on high-resolution displays. On the shared canvas, an effect’s `origin` is in page coordinates, so its particles stay in place on the page while it scrolls.
You can also pass a canvas of your own, to place an effect behind your content, inside a container, or anywhere else on the page:
```js
createEffect({
canvas: document.querySelector("#background"),
origin: { x: 0, y: 0 },
// ...
});
```
With your own canvas, the `origin` is measured from the canvas’ top-left corner instead, and the page’s scroll position doesn’t matter. If you want to emit from an element, [`measureTarget(element, canvas)`](/api/custom_effects/measuretarget/) does this conversion for you. party.js sizes the canvas’ bitmap to match its size on the page, but leaves its styling and placement to you. Effects that share a canvas, the fullscreen one or your own, are drawn together, in the order they were started. Once no effect is drawing on your canvas anymore, it’s cleared and left in place.
How particles are shaded as they turn towards or away from the light source is covered in [Colors & lighting](/concepts/colors-lighting/#lighting).
## When an effect ends
An effect ends by itself once its schedule has run all of its loops and its last particle has died. Every effect returns a handle, and its [`finished`](/api/effects/effect/#finished) promise tells you how the effect ended:
```js
const effect = confetti(button);
const result = await effect.finished;
if (result === "completed") {
// the confetti is gone, for example to navigate to another page
}
```
The promise resolves with:
* `"completed"`, when the effect ended by itself. That includes an effect you called [`end()`](/api/effects/effect/#end) on, which stops emitting new particles, and ends once the ones that are alive have died.
* `"stopped"`, when you called [`stop()`](/api/effects/effect/#stop), which removes all particles right away. The same happens when the effect throws an error while running, for example from a custom behavior. The error is still reported in the console, and other effects keep running.
The promise never rejects. An effect whose schedule loops forever only ends when you end or stop it, and a paused effect with particles left doesn’t end until it’s resumed.
When the user has asked their system for [reduced motion](/quickstart/#reduced-motion), effects are skipped by default. A skipped effect draws nothing, and its `finished` promise resolves with `"completed"` right away, so code that waits for an effect keeps working.
# Samplers & randomness
> How different values for particles are picked, and how to write your own samplers.
No two pieces of confetti look exactly alike: each one gets its own size, color, speed and spin. The values come from **samplers**, small functions that produce a new value every time party.js asks for one. This page explains when that happens, which samplers are built in, and how to write and combine your own.
## Fixed values and samplers
Wherever party.js accepts a [`Sampler`](/api/samplers/sampler/), you can pass one of two things:
* A **fixed value**, like `size: 8`. Every particle gets exactly this value.
* A **sampler function**, like `size: range(4, 12)`. It’s called again for every particle, so each one gets its own value.
```js
import { confetti, range } from "party-js";
confetti(button, { size: 8 }); // every piece is 8px
confetti(button, { size: range(4, 12) }); // every piece is somewhere between 4px and 12px
```
Functions like `range()` don’t return a number themselves. They return the sampler, a function that party.js calls whenever it needs a value. That’s why you can create a sampler once and reuse it across effects.
## When values are picked
Most samplers are called once for each particle, at the moment it spawns. That includes every field of a custom effect’s [`particleInit`](/api/custom_effects/particleinit/): position, velocity, orientation, spin, size, color, shape and lifetime. After that, the values belong to the particle, and only [behaviors](/concepts/behaviors/) change them.
A few values are sampled less often:
* A burst’s `count` is sampled each time the burst fires, so a looping effect can emit a different number of particles every loop.
* Some options of the built-in effects are sampled only once, when the effect starts, and shared by all particles. For example, confetti’s `angle` and `spread` decide the direction of the whole burst, not of each piece.
Don’t confuse samplers with [live values](/api/custom_effects/live/). A sampler produces variety *between* particles. A live value, like an effect’s `origin` or a schedule’s `rate`, is a function without arguments that party.js calls again and again *while the effect runs*, so the effect can track something on the page, such as an element or the window size.
## Built-in samplers
| Sampler | Produces |
| --------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [`range(min, max)`](/api/samplers/range/) | A number between `min` and `max`, with every value equally likely. |
| [`normal(mean, stdDev)`](/api/samplers/normal/) | A number that clusters around `mean`, following a bell curve. Has no hard limits. |
| [`spread(center, deviation)`](/api/samplers/spread/) | A number around `center`, spread evenly across each [batch](#batches). |
| [`pick(values, weights?)`](/api/samplers/pick/) | One of the given values, optionally with weighted chances. |
| [`gradient(colors)`](/api/samplers/gradient/) | A random color along a gradient. |
| [`randomHue({ l, c })`](/api/samplers/randomhue/) | A color with a random hue, but fixed lightness and intensity. |
| [`cone(angle, deviation, speed)`](/api/samplers/cone/) | A velocity in a direction, fanning out by up to `deviation` degrees. |
| [`randomOrientation()`](/api/samplers/randomorientation/) | A random rotation, with every orientation equally likely. |
| [`randomSpin(min, max)`](/api/samplers/randomspin/) | A random spin axis, with a speed between `min` and `max` degrees per second. |
| [`emitFrom(shape)`](/api/custom_effects/emitfrom/) | A position somewhere inside a circle or rectangle. |
As an example, here is a mix of mostly circles with the occasional star, in a range of soft colors:
```js
import { confetti, pick, randomHue } from "party-js";
confetti(button, {
shapes: pick([{ type: "circle" }, { type: "star" }], [4, 1]),
colors: randomHue({ l: 0.65, c: 0.08 }),
});
```
## Writing your own sampler
A sampler is just a function. It receives a [`SamplerContext`](/api/samplers/samplercontext/) and returns a value:
```js
// sizes that alternate between small and large
const alternating = (ctx) => (ctx.index % 2 === 0 ? 6 : 14);
confetti(button, { size: alternating });
```
Tip
When using TypeScript, give the function the [`SamplerFn`](/api/samplers/samplerfn/) type, and the context is typed for you.
The context has three fields:
* `rng` is the effect’s random number generator. Use it instead of `Math.random()`, so your sampler stays [reproducible](#reproducible-randomness).
* `index` counts upwards. For a particle’s initial values, it’s the number of particles the effect has spawned before this one. For a burst’s `count`, it’s the current loop.
* `batch` describes the group of particles spawned together with this one. See [Batches](#batches).
To build a sampler that is based on options, wrap it in an outer function that takes in the options, and returns the sampler itself. All built-in samplers are written this way. For example, a sampler that picks an integer in a given range:
```js
const randomInt = (min, max) => (ctx) =>
Math.floor(min + ctx.rng() * (max - min + 1));
```
You don’t need to clone objects your sampler returns. party.js copies vectors, colors and shapes before they’re used, so returning the same object for every particle is safe.
## Batches
All particles that spawn in the same simulation step form a **batch**. A burst is one batch, and so are several particles of a continuous stream that happen to spawn in the same step. While sampling a particle’s values, `ctx.batch` tells you its position in the batch (`index`) and how many particles the batch has (`size`).
Batches let a sampler coordinate the particles of a burst instead of treating each one on its own. As an example, [`spread()`](/api/samplers/spread/) uses this to split its range into one equal slice per particle in the batch, and give each particle a random value within its own slice. A burst then always covers the whole range evenly, without the clumps and gaps that independent random values can produce. [`cone()`](/api/samplers/cone/) uses `spread()` for its angle, which is why a burst of sparkles always fans out evenly.
You can use batches in your own samplers too. Here, the particles of each burst are placed on a perfect ring:
```js
import { createEffect } from "party-js";
const ring = (radius) => (ctx) => {
const { index, size } = ctx.batch ?? { index: 0, size: 1 };
const angle = (2 * Math.PI * index) / size;
return {
x: Math.cos(angle) * radius,
y: Math.sin(angle) * radius,
z: 0,
};
};
createEffect({
// ...
particleInit: {
position: ring(120),
// ...
},
});
```
`batch` is always set while particle values are sampled, but not while sampling a burst’s `count`, so the type marks it as optional. Falling back to a batch of one keeps the sampler usable everywhere.
## Reproducible randomness
Every effect has its own random number generator, which samplers and behaviors receive as `ctx.rng`. By default, it starts from a random seed, so every run of an effect looks different. Pass a `seed` to [`createEffect()`](/api/custom_effects/createeffect/), and the same seed with the same options produces the same effect every time:
```js
import { createEffect } from "party-js";
createEffect({
// ...
seed: 42,
});
```
This is useful for tests, for screenshots, or when an effect should look identical for every visitor. A few things keep it reproducible:
* **All randomness has to come from `ctx.rng`.** A single sampler or behavior that calls `Math.random()` makes every run different again.
* **The order matters.** The generator produces one sequence of numbers, which is shared between all samplers and behaviors. Adding a sampler, or one that uses more random numbers, shifts the values everything after it receives. The same seed only gives the same result with the same options.
* **Live values have to stay the same.** An origin or emission rate that depends on the window size can change the effect between runs, even with the same seed.
The simulation runs in [fixed steps](/concepts/effects/#time-and-the-simulation-loop), independently of the screen’s frame rate, so a fast and a slow device see the same particles. The exception is a device so slow that party.js has to skip time to keep up.
If you need more control, pass your own generator as `rng` instead. It’s any function that returns a number from 0 (inclusive) to 1 (exclusive), like `Math.random()` does. When both are given, `rng` takes precedence over `seed`.
The built-in effects can take a `seed` too: `confetti(button, { seed: 1 })`.
## Combining samplers
Some samplers accept other samplers as arguments. `cone()` takes its speed as a sampler, so the direction and the speed of each particle can vary independently:
```js
cone(90, 30, range(300, 500));
```
To build your own samplers on top of others, resolve them with [`evaluateSampler()`](/api/samplers/evaluatesampler/). It calls the sampler if it’s a function, or returns it unchanged if it’s a fixed value, so your sampler accepts both:
```js
import { evaluateSampler } from "party-js";
// a sampler that rounds the values of another sampler
const rounded = (sampler) => (ctx) => Math.round(evaluateSampler(sampler, ctx));
confetti(button, { size: rounded(range(4, 12)) });
```
The same approach lets you choose between samplers. `pick()` returns the value it picks as it is, so picking from a list of samplers would hand the sampler itself to the particle, not a value from it. Evaluate the picked sampler as well:
```js
import { confetti, evaluateSampler, pick, range } from "party-js";
// mostly small confetti, with a few large pieces
const sizes = pick([range(4, 8), range(14, 20)], [5, 1]);
const size = (ctx) => evaluateSampler(sizes(ctx), ctx);
confetti(button, { size });
```
Pass the same `ctx` along to the samplers you call, so they use the effect’s random number generator and see the same `index` and `batch`.
# Shapes
> How particles obtain their drawn shape.
The way a particle is drawn depends on its *shape*. party.js ships with a few shapes that cover most effects, like squares, circles and stars, as well as text and images. You can also add your own shapes, as paths or custom draw functions. This page explains how shapes are sized and placed, which ones are built in and how to add your own.
## Shape space
All shapes are drawn in the same coordinate system, called **shape space**. A shape fits into a 1x1 box, centered at (0, 0), so it reaches from -0.5 to 0.5 in both directions. Like on a regular canvas, +y points down.
When a particle is drawn, this box is scaled to the particle’s `size` in pixels, rotated by its orientation, and moved to its position. For example, a circle with a `size` of 10 will be drawn as 10 pixels wide, as would a square. Shapes that aren’t as wide as they are tall, like a narrow strip, fill the box in their longer direction.
## Built-in shapes
The most common shapes for effects are built-in, and easily be used and configured.
[PlaygroundsTry it in the shapes playground](/playgrounds/shapes/)
### Primitives
| Shape | Description |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------ |
| [`square`](/api/particles/squareshape/) | A square, or a rectangle with an `aspectRatio`. `cornerRadius` rounds its corners. |
| [`circle`](/api/particles/circleshape/) | A circle. |
| [`star`](/api/particles/starshape/) | A star with 5 `points`, or as many as you like. `innerRadius` makes its points thinner or wider. |
| [`polygon`](/api/particles/polygonshape/) | A regular polygon with the given number of `sides`. |
`confetti()` uses circles, rounded squares and thin, rounded strips by default, and `sparkles()` uses slim, four-pointed stars. Confetti’s `shapes` option takes a list to pick from:
```js
import { confetti } from "party-js";
confetti(button, {
shapes: [
{ type: "square" },
{ type: "square", aspectRatio: 0.4, cornerRadius: 0.2 },
{ type: "circle" },
{ type: "star", points: 5 },
{ type: "polygon", sides: 6 },
],
});
```
Like other values, shapes are checked before they’re used. A polygon with 2 sides or a negative corner radius throws a [`PartyJSError`](/api/utilities/partyjserror/), either when the effect is created, or for shapes that come from a sampler, when a particle spawns.
### Paths
For any shape you can describe as an outline, use a [`Path2D`](https://developer.mozilla.org/docs/Web/API/Path2D). The path has to be drawn in shape space, inside the 1 by 1 box around (0, 0):
```js
import { confetti } from "party-js";
// a plus sign, drawn inside the 1x1 box around (0, 0)
const plus = new Path2D("M-0.15-0.5h0.3v0.35h0.35v0.3h-0.35v0.35h-0.3v-0.35h-0.35v-0.3h0.35z");
confetti(button, {
shapes: [{ type: "path", path: plus }],
});
```
Icons are also a good source of shapes. Most icons are drawn on a larger grid, like 24 by 24 pixels, so they need to be scaled into the box first:
```js
// an icon from a 24x24 grid, moved to (0, 0) and scaled to a size of 1
const icon = new Path2D();
icon.addPath(new Path2D("M12 2 L22 22 L2 22 Z"), new DOMMatrix().scale(1 / 24).translate(-12, -12));
```
Caution
Only create paths once, and reuse them for every particle. A sampler that creates a new path every time it’s called builds the same shape over and over, which wastes time and memory.
Also, `Path2D` only exists in the browser. If your page is rendered on the server, creating a path at the top level of a module throws there. Create it in an event handler, or the first time an effect starts.
### Text
Single characters or plain text can also be used as a shape.
```js
import { confetti } from "party-js";
confetti(button, {
// ...
shapes: { type: "text", text: "party.js" },
});
```
You can also use emojis, however they will not be affected by the particle’s `color` or lighting. Opacity works fine though.
```js
import { confetti } from "party-js";
confetti(button, {
// ...
shapes: [
{ type: "text", text: "😄" },
{ type: "text", text: "😝" },
],
});
```
Caution
Emoji may wobble slightly while a particle rotates, depending on the browser, because browsers typically snap emoji to the pixel grid. At the sizes and speeds of typical effects it shouldn’t be noticeable.
### Images
Particles can also be pictures, like your logo. Give the image shape a URL, and party.js loads the image for you:
```js
import { confetti } from "party-js";
confetti(button, {
shapes: [{ type: "image", image: "/favicon.svg" }],
size: 24,
});
```
An image keeps its aspect ratio, with its longer side filling the box. It also keeps its own colors: it fades out with the particle, but isn’t tinted by its `color` or lit.
Until the image has loaded, its particles simply aren’t drawn. Loading starts when the first particle spawns, so a large image can miss the first burst. To show it right away, preload it in your page’s ``:
```html
```
Instead of a URL, you can also pass anything a canvas can draw, like an `` that has already loaded, a `