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 `` or an `ImageBitmap`. If you pass an SVG as an ``, give it a `width` and `height`, since some browsers report a size of 0 otherwise. Each URL is only loaded once, and kept for later effects. If it can’t be loaded, party.js reports it once in the console, and the effect plays without those particles. ## Custom drawing functions A custom shape draws the particle with your own function, using the canvas’ [context](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D). The context is already set up when your function is called: it’s moved, rotated and scaled into shape space, and its `fillStyle` is the particle’s lit color, including its opacity. Here, each particle is drawn as three circles, which makes it look like it glows: ```js import { createEffect } from "party-js"; createEffect({ // ... particleInit: { // ... shape: { type: "custom", draw(ctx) { // three circles on top of each other, fainter towards the outside for (const [radius, alpha] of [ [0.5, 0.15], [0.3, 0.35], [0.12, 1], ]) { ctx.globalAlpha = alpha; ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fill(); } }, }, }, // ... lighting: null, }); ``` `globalAlpha` is multiplied with the opacity of the `fillStyle`, so the glow still fades out with the particle. You don’t need to reset anything you change, like `globalAlpha` here: the context is saved before your function is called, and restored afterwards. Your function also receives the particle being drawn, so the drawing can change with it. Here, each particle is a ring that gets thinner as it ages: ```js import { createEffect } from "party-js"; createEffect({ // ... particleInit: { // ... shape: { type: "custom", draw(ctx, particle) { const progress = particle.age / particle.lifetime; ctx.strokeStyle = ctx.fillStyle; ctx.lineWidth = 0.2 * (1 - progress); ctx.beginPath(); ctx.arc(0, 0, 0.4, 0, 2 * Math.PI); ctx.stroke(); }, }, }, // ... lighting: null, }); ``` Only read from the particle. Drawing happens once per frame, not once per simulation step, so to change particles, write a [behavior](/concepts/behaviors/#custom-behaviors). Keep custom drawing functions quick, they run for every particle, on every frame. Prepare anything you can, like images or gradients, outside of the function. ## From 3D to 2D Each particle has a position, a size, and an orientation in 3D. When it’s drawn, party.js takes its shape from [shape space](#shape-space), scales it to the particle’s size, turns it by its orientation, and then looks at the result straight from the front: * **Its position** becomes a point on the canvas, measured from the effect’s origin. Particle space has +y pointing up, the canvas has it pointing down, so party.js flips it. * **Its depth is ignored.** There’s no perspective, so a particle doesn’t get smaller as it moves away, and particles don’t hide each other based on their depth. Particles are drawn in the order they spawned, so newer ones end up on top. * **Its orientation** decides how the flat shape lies in space. Facing you, it’s drawn as it is. As it turns away, it gets narrower, until it’s only a line when you see it edge-on, and then it shows its back side. Here, a row of squares turns around the vertical axis, each one a little further than the one before: ```js import { createEffect } from "party-js"; createEffect({ // ... particleInit: { // ... angularVelocity: { x: 0, y: 120, z: 0 }, }, lighting: null, }); ``` # Create a custom effect > Build your own effects with createEffect(), from a single burst to a toggleable fountain. `confetti()` and `sparkles()` are built on the same function you can use yourself: [`createEffect()`](/api/custom_effects/createeffect/). This guide builds a custom effect step by step, from a few dots at the cursor position to a fountain of particles that can be toggled on and off. It assumes you know the [parts of an effect](/concepts/effects/#anatomy-of-an-effect), and how [samplers](/concepts/samplers/) produce values for each particle. ## The smallest effect An effect needs to know where it happens, when to emit particles, and what they look like. Everything else is optional: ```js import { cone, createEffect, range } from "party-js"; createEffect({ origin: { x: event.pageX, y: event.pageY }, schedule: { bursts: [{ count: 20 }] }, particleInit: { velocity: cone(90, 180, range(100, 300)), size: 8, color: "#ff5a5f", shape: { type: "circle" }, lifetime: 1, }, }); ``` * **`origin`** is where the effect happens, here the point you clicked. On the default fullscreen canvas, it’s in page coordinates, the same ones `event.pageX` and `event.pageY` use. * **`schedule`** emits a single burst of 20 particles, right when the effect starts. * **`particleInit`** describes each particle as it spawns. `size`, `color`, `shape` and `lifetime` are required. Here, the particles also get a velocity: [`cone()`](/api/samplers/cone/) points them upwards, with a deviation of 180 degrees to either side, so in every direction. The position, orientation and spin of a particle are optional. Without them, particles start at the origin, face the viewer, and don’t spin. ## Bursting out of an element Most effects belong to an element, like a button that was clicked. [`measureTarget()`](/api/custom_effects/measuretarget/) measures an element and returns two things: its center as the `origin`, and its `area` to emit from. Passed to [`emitFrom()`](/api/custom_effects/emitfrom/), the area spreads the particles over the whole element. From there, a few more samplers and [behaviors](/concepts/behaviors/) make the particles tumble and fall: ```js import { cone, createEffect, emitFrom, fade, gravity, measureTarget, pick, randomOrientation, randomSpin, range, scale } from "party-js"; const { origin, area } = measureTarget(button); createEffect({ origin, schedule: { bursts: [{ count: 30 }] }, particleInit: { position: emitFrom(area), velocity: cone(90, 30, range(300, 600)), orientation: randomOrientation(), angularVelocity: randomSpin(90, 360), size: range(8, 12), color: pick(["#7dd3fc", "#38bdf8", "#0ea5e9"]), shape: { type: "square", aspectRatio: 0.5 }, lifetime: range(1.5, 2.5), }, behaviors: [gravity(800), scale(0.1, 0), fade(0, 0.5)], }); ``` * [`randomOrientation()`](/api/samplers/randomorientation/) and [`randomSpin()`](/api/samplers/randomspin/) turn each particle in a random direction, and spin it around a random axis. That’s what makes the flat shapes [look three-dimensional](/concepts/shapes/#from-3d-to-2d). * `gravity()` pulls the particles down, `scale()` grows them in quickly, and `fade()` fades them out at the end of their life. `measureTarget()` measures the element once, when it’s called. If the page scrolls afterwards, the particles stay where they were on the page, like the built-in effects do. ## From bursts to streams A burst emits all of its particles at once. A **rate** emits them continuously instead, a number of particles per second. Together with `loops: Infinity`, the schedule never ends, so the effect runs until you end it: ```js import { createEffect, measureTarget } from "party-js"; let fountain; // the first click starts the fountain, the second one turns it off and lets the last drops fall if (fountain) { fountain.end(); fountain = undefined; } else { const { origin, area } = measureTarget(button); fountain = createEffect({ origin, schedule: { rate: 40, loops: Infinity }, // ... }); } ``` [`createEffect()`](/api/custom_effects/createeffect/) returns a handle to the running effect, the same one the built-in effects return. Its [`end()`](/api/effects/effect/#end) method stops the fountain from emitting, and lets the particles that are already in the air finish their flight. Once the last one is gone, the effect ends by itself. To remove the particles right away instead, use [`stop()`](/api/effects/effect/#stop). The [schedule](/concepts/effects/#the-schedule) can do more: several bursts at different times, repeated loops, or a rate that changes while the effect runs. ## Making it reusable To use your effect like a built-in one, wrap it in a function that takes a target and options, and returns the effect: ```js import { createEffect, measureTarget, emitFrom, pick } from "party-js"; export function fountain(target, options = {}) { const { rate = 40, colors = ["#7dd3fc", "#38bdf8", "#0ea5e9"] } = options; const { origin, area } = measureTarget(target); return createEffect({ origin, schedule: { rate, loops: Infinity }, particleInit: { position: emitFrom(area), color: pick(colors), // ... }, // ... }); } const effect = fountain(button, { rate: 60 }); ``` `measureTarget()` accepts an element or a point, just like `confetti()`, so `fountain()` does too. Returning the effect lets the caller pause it, stop it, or wait for it to end with its [`finished`](/api/effects/effect/#finished) promise. Tip In TypeScript, use the [`EffectTarget`](/api/effects/effecttarget/) type for the target, and return an [`Effect`](/api/effects/effect/). ## Following an element The `origin` can also be a function. party.js calls it again on every frame, so the effect can follow an element that moves: ```js createEffect({ origin: () => measureTarget(badge).origin, // ... }); ``` All particles are positioned relative to the origin, so when it moves, the whole effect moves with it, including the particles already in the air. That fits effects that belong to an element, like sparkles around a badge that slides in. It doesn’t leave a trail behind a moving element. Measuring an element on every frame isn’t free, so use this for effects that need it, not for every burst. ## Drawing on your own canvas By default, effects draw on a fullscreen canvas that party.js manages for you. To draw [somewhere else](/concepts/effects/#the-canvas), for example behind your content, pass your own canvas. Its coordinates start at its top-left corner, so pass the canvas to `measureTarget()` as well, and it converts the origin for you: ```js const canvas = document.querySelector("#background"); const { origin, area } = measureTarget(button, canvas); createEffect({ canvas, origin, particleInit: { position: emitFrom(area), // ... }, // ... }); ``` ## Things to keep in mind * **Effects need a browser.** `createEffect()` throws a [`PartyJSError`](/api/utilities/partyjserror/) during server-side rendering. Start effects from event handlers, or after your component has mounted. * **Reduced motion is respected.** When the user has asked their system for [reduced motion](/quickstart/#reduced-motion), custom effects are skipped like the built-in ones. If your particles carry information the user would otherwise miss, pass `reducedMotion: "play"`. * **Seeds make effects repeatable.** Pass a `seed`, and the effect looks the same every time. See [Reproducible randomness](/concepts/samplers/#reproducible-randomness). # Migrating from v2 > How to upgrade your code from v2 to v3. v3 is a complete rewrite of the library. Most of the API changed, but if you only used the built-in effects, upgrading takes a few minutes: `party.confetti(button)` still works. This page goes through everything that changed and shows the v3 equivalent of each v2 feature. If you need to look something up for v2, its documentation is archived at [party-js-v2.pages.dev](https://party-js-v2.pages.dev). Using an AI assistant? If an assistant is helping you migrate, give it [`llms-full.txt`](https://party.js.org/llms-full.txt), to ensure it writes v3 code. ## Summary * **Particles are drawn on a canvas.** v2 created one DOM element per particle. v3 draws all particles onto a single canvas on top of the page, which is more performant. Particles are no longer HTML elements. * **No more namespaces exports.** `party.variation.range()` becomes `range()`, and there’s no default export anymore. * **Variations are now samplers.** They work the same way, but they receive a context, and arrays are no longer picked from automatically (except on built-in effects). * **Colors are strings.** The `Color` class is gone, and you can pass any hex, `rgb()`, `hsl()`, `oklab()` or `oklch()` string. * **Shapes are objects.** `"roundedSquare"` becomes `{ type: "square", cornerRadius: 0.3 }`. * **Effects return a handle.** Instead of an `Emitter`, you get an [`Effect`](/api/effects/effect/) you can stop, pause and await. * **No global scene or settings.** Everything is configured per effect, and custom effects are created with [`createEffect()`](/api/custom_effects/createeffect/). * **Modules are replaced by behaviors.** `ModuleBuilder` is gone, and particles are changed with plain functions instead. * **Sizes are in pixels.** A v2 size of `1` scaled the shape’s own size, a v3 size of `10` is 10 pixels. ## Installing and importing Update the package to v3: ```sh npm install party-js@3 ``` v3 is published as an ES module only, without a CommonJS build or a default export. Import the functions you use by name: v2 ```js import party from "party-js"; // or const party = require("party-js"); party.confetti(button); ``` v3 ```js import { confetti } from "party-js"; confetti(button); ``` If you’d rather keep the `party.` prefix everywhere, `import * as party from "party-js"` gives you a namespace object with the same functions. The script tag works like before. The bundle still lives at `bundle/party.min.js` and puts everything on a global `party` object, so only the version in the URL changes: ```html ``` All functions are available directly on the global, so `party.variation.range(20, 40)` becomes `party.range(20, 40)`. See [Installation](/installation/) for more ways to load the library. ## Using the built-in effects `confetti()` and `sparkles()` still take a target and an options object, and an element as the target works exactly like before: ```js button.addEventListener("click", () => confetti(button)); ``` ### Targets v2 accepted elements, mouse events, and `Rect` and `Circle` objects. v3 accepts an element or a point, in page coordinates: v2 ```js document.addEventListener("click", (event) => { party.confetti(event); }); party.confetti(new party.Rect(200, 300)); ``` v3 ```js document.addEventListener("click", (event) => { confetti({ x: event.pageX, y: event.pageY }); }); confetti({ x: 200, y: 300 }); ``` To emit from a larger area, like the whole screen with `party.Rect.fromScreen()`, write a [custom effect](/guides/custom-effects/) and spawn its particles with [`emitFrom()`](/api/custom_effects/emitfrom/) and a `rect` shape. ### Confetti options | v2 | v3 | Notes | | ---------- | --------------- | --------------------------------------------------------------------------------------------------------------- | | `count` | `count` | The default is now 15-30 instead of 20-40. | | `spread` | `spread` | Still the deviation in degrees, to either side. Most of the confetti now flies close to the center of the cone. | | `speed` | `startVelocity` | Confetti is now slowed down by drag, so v2 values don’t carry over. The default is 800-1500 px/s. | | `size` | `size` | Now in pixels. v2 shapes were 10 pixels, so multiply by 10: `size: 1` becomes `size: 10`. | | `color` | `colors` | An array of color strings, or a sampler. See [Colors](#colors). | | `shapes` | `shapes` | Shape objects instead of names. See [Shapes](#shapes). | | `rotation` | – | Confetti is always turned randomly, and spins as it falls. | | `modules` | – | The built-in effects don’t take behaviors. Use [`createEffect()`](#custom-effects) instead. | | – | `angle` | The direction of the burst, 90 (up) by default. | | – | `lifetime` | How long each piece lives, 2-4 seconds by default. | | – | `gravity` | The strength of gravity for this effect, 800 by default. | | – | `drag` | The speed at which falling confetti stops accelerating. | Since the physics changed, the easiest way to recreate a tuned v2 effect is to start from the v3 defaults and adjust them in the effects playground: [PlaygroundsTry it in the effects playground](/playgrounds/effects/?effect=confetti) ### Sparkles options | v2 | v3 | Notes | | ------------------------------- | --------------- | -------------------------------------------------------------------------------------------------- | | `count` | `count` | Now split into four quick bursts. | | `speed` | `startVelocity` | Sparkles are now slowed down by drag, so v2 values don’t carry over. | | `size` | `size` | Now the size of the largest sparkles, in pixels. Most are smaller. | | `lifetime` | `lifetime` | Unchanged. | | `color` | `colors` | An array of color strings, or a sampler. | | `shapes`, `rotation`, `modules` | – | Sparkles are always four-pointed stars. Build a [custom effect](#custom-effects) for other shapes. | ### Controlling an effect v2 returned the `Emitter` that played the effect. v3 returns an [`Effect`](/api/effects/effect/) handle: ```js const effect = confetti(button); effect.stop(); // removes all particles right away effect.end(); // stops emitting, and lets the particles finish effect.pause(); effect.resume(); await effect.finished; // resolves once the effect is over ``` There’s no `party.scene` anymore, so `party.scene.current.clearEmitters()` and `clearParticles()` have no direct equivalent. Keep the handles of the effects you want to stop, and call `stop()` on them. ## Variations become samplers Variations are now called [samplers](/concepts/samplers/). Like before, an option takes either a fixed value or a function that produces a new value every time it’s called. | v2 | v3 | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `party.variation.range(min, max)` | `range(min, max)` | | `party.variation.skew(value, amount)` | `range(value - amount, value + amount)` | | `party.variation.skewRelative(value, percentage)` | `range(value * (1 - percentage), value * (1 + percentage))` | | `party.variation.gradientSample(gradient)` | `gradient(colors)`, see [Colors](#colors) | | `party.variation.splineSample(spline)` | – | | `party.variation.evaluateVariation(variation)` | `evaluateSampler(sampler, ctx)` | | An array, like `[10, 20, 30]` | `pick([10, 20, 30])` | | A function, like `() => 10` | A function that takes a context, like `(ctx) => 10`, see [Custom samplers](/concepts/samplers/#writing-your-own-sampler) | v3 also brings new samplers, like [`normal()`](/api/samplers/normal/), [`spread()`](/api/samplers/spread/) and [`randomHue()`](/api/samplers/randomhue/), see [Samplers & randomness](/concepts/samplers/). ## Colors The `Color` class is gone. Wherever party.js takes a color, pass a CSS color string instead: | v2 | v3 | | ---------------------------------- | ----------------------------------------------- | | `party.Color.fromHex("#ff5a5f")` | `"#ff5a5f"` | | `party.Color.fromHsl(50, 100, 70)` | `"hsl(50 100% 70%)"` | | `new party.Color(255, 90, 95)` | `"rgb(255 90 95)"` | | `party.Color.white` | `"#fff"` | | `color.mix(other, 0.5)` | `gradient([color, other])` to sample in between | Named colors like `"red"` aren’t supported, to keep the library small. If you need a color object, for example in a [custom behavior](/concepts/behaviors/#custom-behaviors), [`color()`](/api/utilities/color/) converts a string into one. Colors are stored in the Oklab color space now, not RGB. Gradients are created with [`gradient()`](/api/samplers/gradient/), which returns a sampler directly: v2 ```js party.confetti(button, { color: party.variation.gradientSample( party.Gradient.simple(party.Color.fromHex("#ffa68d"), party.Color.fromHex("#fd3a84")), ), }); ``` v3 ```js confetti(button, { colors: gradient(["#ffa68d", "#fd3a84"]), }); ``` Gradient keys with a `time` become stops with an `offset`: `{ time: 0.8, value: color }` is now `{ offset: 0.8, color: "#ff8fa3" }`. v3 blends colors in Oklch instead of RGB, so gradients appear more uniform. A random hue, which v2’s confetti did with `Color.fromHsl(random.randomRange(0, 360), 100, 70)`, is now [`randomHue()`](/api/samplers/randomhue/). It keeps the lightness of all hues equal, which `hsl()` can’t: ```js confetti(button, { colors: randomHue({ l: 0.7, c: 0.15 }) }); ``` See [Colors & lighting](/concepts/colors-lighting/) for more. ## Shapes Since particles are drawn on a canvas, shapes are no longer HTML. The names of the v2 shapes become objects: | v2 | v3 | | -------------------- | --------------------------------------------------------- | | `"square"` | `{ type: "square" }` | | `"rectangle"` | `{ type: "square", aspectRatio: 0.6 }` | | `"roundedSquare"` | `{ type: "square", cornerRadius: 0.3 }` | | `"roundedRectangle"` | `{ type: "square", aspectRatio: 0.6, cornerRadius: 0.3 }` | | `"circle"` | `{ type: "circle" }` | | `"star"` | `{ type: "star" }` | v2 ```js party.confetti(button, { shapes: ["star", "roundedSquare"] }); ``` v3 ```js confetti(button, { shapes: [{ type: "star" }, { type: "square", cornerRadius: 0.3 }], }); ``` Custom shapes registered in `party.resolvableShapes`, and HTML elements passed as shapes, need to be rebuilt with one of the new shape types: * An SVG `` becomes a [`path`](/concepts/shapes/#paths) shape. Its `d` attribute works with `new Path2D(d)`, but it has to be scaled into the 1 by 1 box shapes are drawn in. The [hearts example](#example-hearts) below shows how. * An emoji or a character becomes a [`text`](/concepts/shapes/#text) shape. * An `` becomes an [`image`](/concepts/shapes/#images) shape. * Anything else can be drawn with a [`custom`](/concepts/shapes/#custom-drawing-functions) shape and the canvas API. There are new primitives as well, like stars with any number of points and regular polygons. [PlaygroundsTry it in the shapes playground](/playgrounds/shapes/) ## Global settings `party.settings` is gone. Instead, settings are applied locally: | v2 | v3 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `settings.gravity` | Set per effect, with confetti’s `gravity` option or the [`gravity()`](/api/behaviors/gravity/) behavior. | | `settings.respectReducedMotion` | Still respected by default. To play effects anyway, call [`setDefaultReducedMotion("play")`](/api/effects/setdefaultreducedmotion/), or pass `reducedMotion: "play"` to a single effect. | | `settings.zIndex` | Not needed: the canvas is shown above all other content, including dialogs. To draw somewhere else, [pass your own canvas](/concepts/effects/#the-canvas). | | `settings.debug` | Removed. | `party.forceInit()` is gone too, as there is nothing to initialize: the canvas is created when the first effect starts, and removed again once the last one ends. ## Custom effects In v2, custom effects were created with `party.scene.current.createEmitter()`, split into emitter, emission and renderer options. In v3, they’re created with [`createEffect()`](/api/custom_effects/createeffect/), which describes an effect with four main options: an `origin`, a `schedule`, a `particleInit` for each particle’s starting values, and a list of `behaviors`. [How an effect works](/concepts/effects/) explains them in detail. ### Option by option | v2 | v3 | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `emitterOptions.duration` | `schedule.duration`, now 1 second by default instead of 5. | | `emitterOptions.loops` | `schedule.loops`. Use `Infinity` instead of `-1` to loop forever. | | `emitterOptions.useGravity` | Add [`gravity()`](/api/behaviors/gravity/) to `behaviors`. v3 particles don’t fall unless told to do so. | | `emitterOptions.modules` | `behaviors`, see [Modules become behaviors](#modules-become-behaviors). | | `emitterOptions.maxParticles` | Removed. | | `emitterOptions.despawningRules` | Removed. Particles die once their `age` reaches their `lifetime`, and other rules can be implemented via [behaviors](/concepts/behaviors/). | | `emissionOptions.rate` | `schedule.rate`, now 0 by default instead of 10, so `rate: 0` isn’t needed for bursts. | | `emissionOptions.bursts` | `schedule.bursts`. A burst’s `time` is optional now, and `probability` was removed. | | `emissionOptions.sourceSampler` | `origin` and `particleInit.position`, see [below](#positions-and-directions). | | `emissionOptions.angle` and `initialSpeed` | `particleInit.velocity`, for example with [`cone()`](/api/samplers/cone/). | | `emissionOptions.initialLifetime` | `particleInit.lifetime`, now required. | | `emissionOptions.initialSize` | `particleInit.size` in pixels, now required. | | `emissionOptions.initialColor` | `particleInit.color`, now required. | | `emissionOptions.initialRotation` | `particleInit.orientation`, for example with [`randomOrientation()`](/api/samplers/randomorientation/). | | `rendererOptions.shapeFactory` | `particleInit.shape`, now required. | | `rendererOptions.applyLighting` | `lighting`, see [Lighting](/concepts/colors-lighting/#lighting). Pass `null` to turn it off. | | `rendererOptions.applyColor`, `applyOpacity`, `applyTransform` | Removed. To change how particles are drawn, use a [custom shape](/concepts/shapes/#custom-drawing-functions). | Spinning particles no longer need a module: give them an `angularVelocity`, in degrees per second around an axis, for example with [`randomSpin()`](/api/samplers/randomspin/). ### Positions and directions v2 emitted particles at absolute positions on the page. In v3, an effect has an `origin`, and particle positions are relative to it. [`measureTarget()`](/api/custom_effects/measuretarget/) turns an element or a point into an origin and an area, and [`emitFrom()`](/api/custom_effects/emitfrom/) spreads the particles over that area: v2 ```js party.scene.current.createEmitter({ emissionOptions: { sourceSampler: party.sources.dynamicSource(button), // ... }, }); ``` v3 ```js const { origin, area } = measureTarget(button); createEffect({ origin, particleInit: { position: emitFrom(area), // ... }, // ... }); ``` Positions, velocities and angles are now in particle space, where +y points **up**, not down like on the page. An angle of 90 points up, so v2 angles need their sign flipped: v2’s `-90` is `90` in v3. v2 ```js emissionOptions: { angle: party.variation.skew(-90, 45), initialSpeed: party.variation.range(300, 600), }, ``` v3 ```js particleInit: { velocity: cone(90, 45, range(300, 600)), }, ``` ### Modules become behaviors v2 modules were built with `ModuleBuilder` and were very limited. In v3, a [behavior](/concepts/behaviors/) is a function that receives the particle on every simulation step, and can change anything about it. The common modules have built-in replacements: | v2 module | v3 behavior | | ------------------------------------ | -------------------------------------------------- | | Growing the size from 0 at the start | [`scale(inDuration, 0)`](/api/behaviors/scale/) | | Shrinking the size to 0 at the end | [`scale(0, outDuration)`](/api/behaviors/scale/) | | Fading out the opacity at the end | [`fade(0, outDuration)`](/api/behaviors/fade/) | | Rotating at a constant speed | `particleInit.angularVelocity`, no behavior needed | Anything else becomes a [custom behavior](/concepts/behaviors/#custom-behaviors). The particle has an `age`, which counts up from 0, and a `lifetime`, which stays the same. v2’s `lifetime` counted down instead, so its `"lifetime"` factor is `particle.age` in v3, and its `"relativeLifetime"` factor is `particle.age / particle.lifetime`. A module marked `.relative()` worked relative to the particle’s starting value. In v3, a behavior that needs the starting value stores it when the particle spawns, using an `init` function: v2 ```js new party.ModuleBuilder() .drive("size") .by((t) => 1 - t) .through("relativeLifetime") .relative() .build(); ``` v3 ```js const shrink = () => { const startSize = new WeakMap(); return { init: (particle) => startSize.set(particle, particle.size), update: (particle) => { particle.size = startSize.get(particle) * (1 - particle.age / particle.lifetime); }, }; }; ``` Opacity is no longer a separate property. It’s the `alpha` of the particle’s color, which is what [`fade()`](/api/behaviors/fade/) changes. ### Example: hearts To put it all together, here is the hearts effect from the v2 documentation, and the same effect in v3: v2 ```js const heartPath = document.createElementNS("http://www.w3.org/2000/svg", "path"); heartPath.setAttribute("d", "M316.722,29.761c66.852,0,121.053,54.202,121.053,121.041c0,110.478-218.893,257.212-218.893,257.212S0,266.569,0,150.801 C0,67.584,54.202,29.761,121.041,29.761c40.262,0,75.827,19.745,97.841,49.976C240.899,49.506,276.47,29.761,316.722,29.761z"); const heartShape = document.createElementNS("http://www.w3.org/2000/svg", "svg"); heartShape.setAttribute("viewBox", "0 0 512 512"); heartShape.setAttribute("height", "20"); heartShape.setAttribute("width", "20"); heartShape.appendChild(heartPath); party.scene.current.createEmitter({ emitterOptions: { loops: 1, useGravity: false, modules: [ new party.ModuleBuilder() .drive("size") .by((t) => 0.5 + 0.3 * (Math.cos(t * 10) + 1)) .build(), new party.ModuleBuilder() .drive("rotation") .by((t) => new party.Vector(0, 0, 100).scale(t)) .relative() .build(), ], }, emissionOptions: { rate: 0, bursts: [{ time: 0, count: party.variation.skew(20, 10) }], sourceSampler: party.sources.dynamicSource(button), angle: party.variation.range(0, 360), initialSpeed: 400, initialColor: party.variation.gradientSample( party.Gradient.simple(party.Color.fromHex("#ffa68d"), party.Color.fromHex("#fd3a84")), ), }, rendererOptions: { shapeFactory: heartShape, applyLighting: undefined, }, }); ``` v3 ```js import { cone, createEffect, emitFrom, fade, gradient, measureTarget, range } from "party-js"; let heart; // the heart from above, moved to (0, 0) and scaled into the 1x1 box function heartPath() { const path = new Path2D(); path.addPath( new Path2D("M316.722,29.761c66.852,0,121.053,54.202,121.053,121.041c0,110.478-218.893,257.212-218.893,257.212S0,266.569,0,150.801 C0,67.584,54.202,29.761,121.041,29.761c40.262,0,75.827,19.745,97.841,49.976C240.899,49.506,276.47,29.761,316.722,29.761z"), new DOMMatrix().scale(1 / 438).translate(-219, -219), ); return path; } // replaces the size module: pulses between 10 and 22 pixels const pulse = (particle) => { particle.size = 20 * (0.5 + 0.3 * (Math.cos(particle.age * 10) + 1)); }; export function hearts(target) { heart ??= heartPath(); const { origin, area } = measureTarget(target); return createEffect({ origin, schedule: { bursts: [{ count: range(10, 30) }] }, particleInit: { position: emitFrom(area), velocity: cone(0, 180, 400), angularVelocity: { x: 0, y: 0, z: 100 }, size: 20, color: gradient(["#ffa68d", "#fd3a84"]), shape: { type: "path", path: heart }, lifetime: 2, }, behaviors: [pulse, fade(0, 0.5)], lighting: null, }); } ``` A few things changed on the way: * The path is created once, the first time the effect runs, since `Path2D` doesn’t exist during server-side rendering. * `useGravity: false` needs no replacement, since v3 particles only fall with `gravity()`. * `cone(0, 180, 400)` points right, and fans out by 180 degrees to either side, so in every direction, like v2’s `range(0, 360)`. * The v2 hearts lived for 5 seconds, but were usually off-screen long before. Here they live for 2 seconds, and fade out over the last half. [Create a custom effect](/guides/custom-effects/) walks through building effects like this step by step. ## Removed utilities v3 no longer exports its helpers. If you used them, here’s what to use instead: * **`party.math`**: use `Math` directly, or a few lines of your own for `lerp()` and `clamp()`. * **`party.random`**: inside samplers and behaviors, use `ctx.rng()` instead of `Math.random()`. `pick()` is now a [sampler](/api/samplers/pick/). * **`party.Vector`**, **`party.Rect`**, **`party.Circle`**: vectors and points are plain objects, like `{ x: 10, y: 20 }`. * **`party.Gradient`**, **`party.NumericSpline`**: use [`gradient()`](/api/samplers/gradient/) for colors. To shape a value over time, use an [easing](/concepts/behaviors/#easing) or a custom behavior. * **`party.util`**, **`party.Emitter`**, **`party.Particle`**: removed. `Particle` is still available as a [type](/api/particles/particle/). ## Server-side rendering Like v2, v3 can be imported on the server, but effects can only run in the browser. Calling an effect during server-side rendering throws a [`PartyJSError`](/api/utilities/partyjserror/), so start effects from event handlers or after your component has mounted. See [With a framework](/installation/#with-a-framework) for examples. # party.js Quick to start ## One call is all it takes Give party.js an element and let the confetti burst out of it! Every option has a sensible default, so your first call fits on a single line. One lineWith options ```js import { confetti } from "party-js"; confetti(button); ``` ```js import { confetti, range } from "party-js"; confetti(button, { count: range(60, 90), spread: 100, startVelocity: range(1200, 2000), }); ``` Effects ## Ready-made, and designed to be customized Each built-in effect is one function with typed options. When none of them fits, build your own from the same parts. Fire confetti ### confetti() Paper-like confetti that bursts in an upwards cone. [Confetti docs](/effects/confetti/) Sparkle ### sparkles() Golden sparkles that burst outwards and glint. [Sparkles docs](/effects/sparkles/) ```ts createEffect({ origin: { x, y }, schedule: { /* ... */ }, particleInit: { /* ... */ }, behaviors: [/* ... */], }); ``` ### Your own effect The built-in effects are made with `createEffect()`. So is yours: pick an emitter, samplers and behaviors. [Create a custom effect](/guides/custom-effects/) Why party.js ## What you get ### Customizable all the way down Samplers vary any value, behaviors change how particles move, and custom shapes draw whatever a canvas can. [How an effect works](/concepts/effects/) ### No dependencies Nothing else to install and nothing to keep up to date. It runs on the canvas your browser already has. [Installation](/installation/) ### Typed from the start Written in TypeScript. Every option is typed and documented, right where you write your code. [API reference](/api/) ### Respects reduced motion Effects skip when a visitor's system asks for less motion. You decide per effect whether it should play anyway. [Reduced motion](/quickstart/#reduced-motion) Playgrounds ## Try it before you install Tune every option with a live preview, then copy the code it generates. ### [Effects playground](/playgrounds/effects/) [Count, angle, speed, colors and shapes, with a live burst on every change.](/playgrounds/effects/) ### [Shapes playground](/playgrounds/shapes/) [See a particle shape up close and at real size before you use it in an effect.](/playgrounds/shapes/) v2v3 ## Coming from v2? v3 is a rewrite with a new API. The migration guide will help you to upgrade your code to the new version. [Migration guide](/migrating-from-v2/) ![](/_astro/confetti-decor.BHir54VU_ZFldEc.svg) ## Ready to start? Install it, then follow the quickstart to fire your first effect! $`npm install party-js`Copy[Quickstart](/quickstart/) # Behavior > Changes a particle over its lifetime. ```ts type Behavior = BehaviorUpdate | BehaviorObject; ``` Modifies a particle over its lifetime, for example gravity, drag or fading. Either a plain update function, called for every particle on every step, or a [BehaviorObject](/api/behaviors/behaviorobject/) when the behavior also needs to perform setup for each new particle. Behaviors run in the order they are listed in. # BehaviorInit > Prepares a newly spawned particle for a behavior. ```ts type BehaviorInit = (particle: Particle, ctx: BehaviorInitContext) => void; ``` A function that prepares a newly spawned particle for a behavior. Called once per particle right after it has been constructed, but before its first update. Initializations are called in the order that the behaviors are listed in. A common use case is to remember initial particle data or to choose a random initial value for a behavior via the random number generator. ## Parameters * `particle`[`Particle`](/api/particles/particle/) The new particle. * `ctx`[`BehaviorInitContext`](/api/behaviors/behaviorinitcontext/) The context supplied to the initialization, including the random number generator. # BehaviorInitContext > Context passed to a behavior when a particle spawns. Passed to [BehaviorObject.init](/api/behaviors/behaviorobject/#init) once, after the particle spawns and before its first update. ## Properties * `rng`[`Rng`](/api/utilities/rng/) The effect’s random number generator. Use it in place of `Math.random()` to keep seeded effects reproducible. # BehaviorObject > A behavior with an optional setup step for each particle. A behavior that can also perform initialization when the particle is spawned. To remember something per particle, create a [WeakMap](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) keyed by particle inside your behavior’s factory function, so that every instance of the behavior gets its own map. ## Example ```ts const shrink = (): Behavior => { const startSize = new WeakMap(); return { init(particle) { startSize.set(particle, particle.size); }, update(particle) { const start = startSize.get(particle) as number; particle.size = start * (1 - particle.age / particle.lifetime); }, }; }; ``` ## Properties * `init`optional[`BehaviorInit`](/api/behaviors/behaviorinit/) The initialization function of the behavior, called once for each particle, right after it spawns. * `update`[`BehaviorUpdate`](/api/behaviors/behaviorupdate/) The update function of the behavior, called on every particle every simulation step. # BehaviorUpdate > Updates a particle by one simulation step. ```ts type BehaviorUpdate = (particle: Particle, ctx: BehaviorUpdateContext) => void; ``` A function that updates a particle by a single simulation step. Called for every particle on every step, in the order that the behaviors are listed in. Any “per-second” changes should be scaled by `ctx.dt` to make the behavior independent of the step size. ## Parameters * `particle`[`Particle`](/api/particles/particle/) The particle to be updated. * `ctx`[`BehaviorUpdateContext`](/api/behaviors/behaviorupdatecontext/) The context supplied to the update, including the random number generator and the time step. # BehaviorUpdateContext > Context passed to a behavior on every simulation step. Passed to a behavior’s update function on every simulation step. ## Properties * `dt``number` The length of this step, in seconds. * `rng`[`Rng`](/api/utilities/rng/) The effect’s random number generator. Use it in place of `Math.random()` to keep seeded effects reproducible. # drag() > Slows particles down in proportion to their speed. see [Terminal Velocity - Falling with a Linear Drag Force](https://lampz.tugraz.at/~hadley/physikm/script/motion/terminal.en.php) ```ts function drag(rate: Sampler, edgeRatio?: number): Behavior; ``` Creates a behavior that applies air resistance proportional to a particle’s speed. Every second, a particle loses the fraction `rate` of its velocity. A fast particle therefore slows down sharply at first, then more and more gently. Together with [gravity()](/api/behaviors/gravity/), a falling particle speeds up until it reaches its terminal velocity of `gravity / rate`, so if you know how fast particles should fall, use `drag(gravity / terminalVelocity)`. The rate is sampled once for each particle, when it spawns. Flat particles like paper feel more resistance when they move face-on than when they move edge-on. Set `edgeRatio` below 1 to simulate this: a tilted particle then glides sideways while it falls, and as it tumbles, the glide reverses, so it sways back and forth. The face is the plane of the particle’s shape, so this needs particles that spin, for example with [randomSpin()](/api/samplers/randomspin/). On average over all orientations, the drag stays at `rate`, so the terminal velocity stays close to `gravity / rate`. ## Parameters * `rate`[`Sampler`](/api/samplers/sampler/)<`number`> The fraction of its velocity a particle loses per second, in 1/s. Values between 2 and 10 are usually sensible. Sampled for each particle. * `edgeRatio`optional`number`default`1` How much drag a particle feels when it moves edge-on, relative to face-on. 1 makes drag the same in every direction. Values between 0.3 and 0.5 give a paper-like flutter, while lower values make particles glide far to the side. Defaults to 1. ## Returns * [`Behavior`](/api/behaviors/behavior/) ## Example ```ts // Falls at most 160px/s under gravity(800), and flutters like paper. const behaviors = [gravity(800), drag(800 / 160, 0.4)]; ``` # Easing > Reshapes progress to make transitions start or end softly. ```ts type Easing = (t: number) => number; ``` A function that reshapes progress from 0 to 1, used by behaviors like [fade()](/api/behaviors/fade/) and [scale()](/api/behaviors/scale/) to make a transition start or end softly. It receives a progress `t` from 0 to 1 and returns the eased value. It is expected to return 0 at `t = 0` and 1 at `t = 1`. In between, its shape determines how fast the transition moves. ## Parameters * `t``number` The received progress from 0 to 1. ## Returns * `number` The reshaped progress. ## Example ```ts // A custom ease that starts even more slowly than sineIn. const cubicIn: Easing = (t) => t ** 3; fade(0.2, 0.5, cubicIn); ``` # fade() > Fades a particle in and out. ```ts function fade(inDuration: number, outDuration: number, ease?: Easing): Behavior; ``` Creates a behavior that fades a particle’s opacity in and out over the specified durations. The fade-in takes place during the first `inDuration` seconds of a particle’s lifetime, while the fade-out happens during the last `outDuration` seconds of the particle’s lifetime. The supplied easing is applied forwards when fading in, and in reverse when fading out. ## Parameters * `inDuration``number` The duration in seconds it takes for the particle to fade in fully, or 0 if no fade-in should be applied. * `outDuration``number` The duration in seconds it takes for the particle to fade out fully, or 0 if no fade-out should be applied. * `ease`optional[`Easing`](/api/behaviors/easing/) How the transition progresses. Defaults to [linear()](/api/behaviors/linear/). ## Returns * [`Behavior`](/api/behaviors/behavior/) # gravity() > Pulls particles down with a constant acceleration. ```ts function gravity(strength: number): Behavior; ``` Creates a behavior that continuously accelerates a particle downward by a constant amount, simulating gravity. ## Parameters * `strength``number` The downward acceleration, in px/s². A positive value pulls towards -y in particle space, which is down in screen space. ## Returns * [`Behavior`](/api/behaviors/behavior/) # linear() > Moves at a constant rate. ```ts function linear(): Easing; ``` Creates an easing that moves at a constant rate. ## Returns * [`Easing`](/api/behaviors/easing/) # scale() > Scales a particle in and out. ```ts function scale( inDuration: number, outDuration: number, ease?: Easing, ): Behavior; ``` Creates a behavior that grows a particle from 0 to its sampled size and shrinks it back to 0 over the specified durations. The growing takes place during the first `inDuration` seconds of a particle’s lifetime, while the shrinking happens during the last `outDuration` seconds of the particle’s lifetime. The supplied easing is applied forwards when growing, and in reverse when shrinking. ## Parameters * `inDuration``number` The duration in seconds it takes for the particle to grow from 0 to its sampled size, or 0 if it should start at its sampled size. * `outDuration``number` The duration in seconds it takes for the particle to shrink back to 0, or 0 if it should end at its sampled size. * `ease`optional[`Easing`](/api/behaviors/easing/) How the transition progresses. Defaults to [linear()](/api/behaviors/linear/). ## Returns * [`Behavior`](/api/behaviors/behavior/) # sineIn() > Starts slowly and speeds up. see [easings.net: easeInSine](https://easings.net/#easeInSine) ```ts function sineIn(): Easing; ``` Creates an easing that starts slowly and speeds up towards the end. ## Returns * [`Easing`](/api/behaviors/easing/) # sineInOut() > Starts slowly, speeds up and slows down again. see [easings.net: easeInOutSine](https://easings.net/#easeInOutSine) ```ts function sineInOut(): Easing; ``` Creates an easing that starts slowly, speeds up towards the middle and slows down at the end. ## Returns * [`Easing`](/api/behaviors/easing/) # sineOut() > Starts quickly and slows down. see [easings.net: easeOutSine](https://easings.net/#easeOutSine) ```ts function sineOut(): Easing; ``` Creates an easing that starts quickly and slows down towards the end. ## Returns * [`Easing`](/api/behaviors/easing/) # twinkle() > Makes particles glint now and then, like glitter. ```ts function twinkle(options?: TwinkleOptions): Behavior; ``` Creates a behavior that makes particles twinkle occasionally. Each particle glints a few times during its life, at random moments: for a short while, it grows a little and flashes towards white, then settles back. Between glints, it looks as it would without this behavior. The glint is applied on top of the particle’s size and color, so it works together with behaviors that change them. List it after [scale()](/api/behaviors/scale/), which sets the size from scratch on every step and would otherwise overwrite the glint. ## Parameters * `options`optional[`TwinkleOptions`](/api/behaviors/twinkleoptions/)default`{}` How often and how strongly particles glint. See [TwinkleOptions](/api/behaviors/twinkleoptions/). ## Returns * [`Behavior`](/api/behaviors/behavior/) ## Throws * [PartyJSError](/api/utilities/partyjserror/) If an option is out of range. ## Example ```ts const behaviors = [scale(0.05, 0.25), twinkle({ glints: 2, brightness: 0.8 })]; ``` # TwinkleOptions > How often and how strongly particles twinkle. Options for [twinkle()](/api/behaviors/twinkle/). ## Properties * `brightness`optional`number`default`0.6` How far a particle’s color moves towards white at the peak of a glint, from 0 (not at all) to 1 (fully white). * `glints`optional`number`default`1.5` How many glints a particle catches per second, on average. A particle that lives for one second with the default of 1.5 glints once or twice, at random moments. * `length`optional`number`default`0.22` How long a single glint lasts, from start to end, in seconds. Longer glints look softer. * `size`optional`number`default`0.25` How much a particle grows at the peak of a glint, relative to its size. `0.25` makes it 25% larger. # createEffect() > Creates and starts a custom effect. ```ts function createEffect(options: CreateEffectOptions): Effect; ``` Creates and starts a custom effect, using the provided options. The built-in effects like [confetti()](/api/effects/confetti/) are made using this function. You can use it directly if your needs are not covered by them. ## Parameters * `options`[`CreateEffectOptions`](/api/custom_effects/createeffectoptions/) Everything that defines the effect. ## Returns * [`Effect`](/api/effects/effect/) A handle to pause, resume or stop the effect early. ## Example ```ts createEffect({ origin: { x: 200, y: 300 }, schedule: { bursts: [{ count: 30 }] }, particleInit: { position: emitFrom({ type: "disk", radius: 20 }), 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(2, 3), }, behaviors: [gravity(800), fade(0, 0.5)], }); ``` # CreateEffectOptions > Everything that defines a custom effect. extends [`BaseEffectOptions`](/api/effects/baseeffectoptions/) Options for [createEffect()](/api/custom_effects/createeffect/), with everything that defines a custom effect: where it happens, when particles are emitted, how they start out and how they change. ## Properties * `behaviors`optional[`Behavior`](/api/behaviors/behavior/)\[] How particles change over their lifetime, run in this order on every simulation step. See [Behavior](/api/behaviors/behavior/). * `canvas`optional[`HTMLCanvasElement`](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement) A canvas to draw onto. If none is provided, party.js draws onto a fullscreen canvas it shares between all effects, and removes it once no effect is using it anymore. If provided, positions are measured from the canvas’ top-left corner: the built-in effects measure their target relative to it, and a custom effect’s origin is given in its coordinates (see [measureTarget()](/api/custom_effects/measuretarget/)). * `light`optional[`Live`](/api/custom_effects/live/)<[`Vec3`](/api/utilities/vec3/)>default`{ x: 0, y: 0, z: 1 }` The direction that light comes from, in particle space. The vector’s length does not matter. This value is read every frame. The default value points straight from the viewer. * `lighting`optional[`LightingFn`](/api/custom_effects/lightingfn/) | `null`default`createLighting()` How a particle’s color changes with the angle between its face and the light. See [createLighting()](/api/custom_effects/createlighting/). Pass `null` to disable lighting. * `origin`[`Live`](/api/custom_effects/live/)<[`Vec2`](/api/utilities/vec2/)> The point particle positions are measured from. Read again on every frame, so a function can make the whole effect follow something or, for example, react to the window size. Without a `canvas`, party.js draws onto its own fullscreen canvas, and the origin is in page coordinates, i.e. pixels from the top-left of the document, with +y pointing down. With a `canvas`, it’s in that canvas’ coordinate system instead, i.e. pixels from its top-left corner. To start the effect at an element, use [measureTarget()](/api/custom_effects/measuretarget/), which also handles the conversion to a canvas’ coordinates. * `particleInit`[`ParticleInit`](/api/custom_effects/particleinit/) How new particles start out. * `reducedMotion`optional[`ReducedMotion`](/api/effects/reducedmotion/) What the effect does when the user has asked their system for reduced motion. A skipped effect draws nothing, and the `finished` promise on the effect handle resolves as “completed” after `createEffect()` returns, unless you stop the effect immediately. See [ReducedMotion](/api/effects/reducedmotion/) for more information. Without this option, the default set with [setDefaultReducedMotion()](/api/effects/setdefaultreducedmotion/) is used, which is `"skip"` unless you changed it. * `rng`optional[`Rng`](/api/utilities/rng/) A random number generator to use instead of the built-in one. This takes precedence over `seed`. * `schedule`[`EmissionSchedule`](/api/custom_effects/emissionschedule/) When and how many particles are emitted. * `seed`optional`number` A seed for the effect’s random number generator. The same seed with the same options produces the same visuals each time. Without one, a random seed is generated and every run of the effect looks different. # createLighting() > Creates a lighting function that brightens particles facing the light. ```ts function createLighting(options?: CreateLightingOptions): LightingFn; ``` Creates a [LightingFn](/api/custom_effects/lightingfn/) that scales a color’s lightness by how directly the particle faces the light, from both sides alike. The lightness of a particle is multiplied by a value from `options.ambient` to `options.peak`, which is calculated via interpolation by the lighting coefficient. ## Parameters * `options`optional[`CreateLightingOptions`](/api/custom_effects/createlightingoptions/) The ambient and peak lightness factors. ## Returns * [`LightingFn`](/api/custom_effects/lightingfn/) # CreateLightingOptions > The strength of ambient and directional light. Options for [createLighting()](/api/custom_effects/createlighting/). ## Properties * `ambient`optional`number`default`0.5` The lightness factor for a particle seen edge-on to the light. * `peak`optional`number`default`1` The lightness factor for a particle facing the light directly. # DiskEmissionShape > A circular area that particles spawn from. A filled circle that particles spawn from, with every point inside it equally likely. ## Properties * `center`optional[`Vec2`](/api/utilities/vec2/)default`{ x: 0, y: 0 }` The center of the circle, in pixels from the origin. * `radius``number` The radius of the circle, in pixels. * `type``"disk"` # EmissionBurst > A group of particles emitted all at once. A group of particles emitted all at once, at a set time in each loop of an [EmissionSchedule](/api/custom_effects/emissionschedule/). ## Properties * `count`[`Sampler`](/api/samplers/sampler/)<`number`> How many particles the burst emits. Sampled once each time the burst fires, with `ctx.index` set to the current loop. The sampled number will be rounded to the nearest integer. * `time`optional`number`default`0` When the burst fires, in seconds from the start of each loop. Must be at least 0 and at most the schedule’s `duration`, or an error will be thrown as the burst would never fire. # EmissionSchedule > When and how many particles an effect emits. When and how many particles an effect emits. A schedule runs for `duration` seconds, `loops` times in a row. During that time, particles are emitted continuously at `rate` per second, and each burst fires at its set time once per loop. The effect ends once all loops have run and the last particle has expired (i.e. died). ## Example ```ts // A single burst of 40 particles. const scheduleA = { bursts: [{ count: 40 }] }; // A steady stream of 20 particles per second, running forever. const scheduleB = { loops: Infinity, rate: 20 }; ``` ## Properties * `bursts`optional[`EmissionBurst`](/api/custom_effects/emissionburst/)\[]default`[]` Groups of particles emitted all at once, each fired once per loop. * `duration`optional`number`default`1` The length of one loop, in seconds. Must be positive and finite. * `loops`optional`number`default`1` How many loops the schedule runs. Use `Infinity` for an effect that runs until it’s [ended](/api/effects/effect/#end) or [stopped](/api/effects/effect/#stop). * `rate`optional[`Live`](/api/custom_effects/live/)<`number`>default`0` How many particles to emit per second, continuously. This is read on every simulation step, so a function can speed the stream up or slow it down, or (for example) make it dependent on the screen size. While it’s 0, the stream pauses, and it picks up at the same pace once the rate is raised again, without making up for the time in between. # EmissionShape > An area that particles spawn from. ```ts type EmissionShape = DiskEmissionShape | RectEmissionShape; ``` An area that particles spawn from, for use with [emitFrom()](/api/custom_effects/emitfrom/). Positions are in particle space, i.e. in pixels from the effect’s origin, with +y pointing upwards. # emitFrom() > Spawns particles from an area. ```ts function emitFrom(shape: Live): SamplerFn; ``` Creates a sampler for particle positions spread across an area. The shape is [Live](/api/custom_effects/live/): pass a function to make the follow something that changes, for example the window width. It’s read again for every particle that spawns. ## Parameters * `shape`[`Live`](/api/custom_effects/live/)<[`EmissionShape`](/api/custom_effects/emissionshape/)> The area to spawn particles from. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<[`Vec3`](/api/utilities/vec3/)> A sampler for [ParticleInit.position](/api/custom_effects/particleinit/#position). ## Example ```ts // Along a line across the full width of the window. const positionSampler = emitFrom(() => ({ type: "rect", width: window.innerWidth, height: 0, })); ``` # LightingFn > Adjusts a particle's color for lighting. ```ts type LightingFn = (color: Readonly, coefficient: number) => Color; ``` A function that adjusts a particle’s color to account for lighting, called for every particle on every frame. It receives the particle’s color and how directly its face points towards the light, from -1 to 1, with 0 meaning edge-on. It must return a new color instance, as it should not modify the particle’s own color. ## Parameters * * `color`[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)<[`Color`](/api/utilities/color-type/)> * `coefficient``number` ## Returns * [`Color`](/api/utilities/color-type/) # Live > A value that can change while an effect runs. ```ts type Live = T | (() => T); ``` A value that can change while an effect runs: either a fixed value, or a function that party.js calls again each time it needs the value. Use a function to follow something outside of the effect, for example the window size, the scroll position or an element that moves its position. Unlike a [Sampler](/api/samplers/sampler/), the function receives no context. It is not about variety between particles, but rather about reacting to page state. ## Type Parameters * `T` ## Example ```ts // Keep emitting from the center of the window, even when it's resized. const origin = () => ({ x: window.innerWidth / 2, y: window.innerHeight / 2 }); ``` # MeasuredTarget > An effect's origin and the area its particles spawn from. Where an effect happens and which area its particles spawn from, as returned by [measureTarget()](/api/custom_effects/measuretarget/). ## Properties * `area`[`EmissionShape`](/api/custom_effects/emissionshape/) The area particles spawn from, relative to the `origin`, for [emitFrom()](/api/custom_effects/emitfrom/): the element’s whole area, or a single point. * `origin`[`Vec2`](/api/utilities/vec2/) The effect’s origin, for [CreateEffectOptions.origin](/api/custom_effects/createeffectoptions/#origin): the target’s center, in page coordinates, or in the canvas’ coordinates if a canvas was given. # measureTarget() > Turns an element or point into an origin and an emission area. ```ts function measureTarget( target: EffectTarget, canvas?: HTMLCanvasElement, ): MeasuredTarget; ``` Turns an element or a point into an origin and an emission area for [createEffect()](/api/custom_effects/createeffect/). Use it to make a custom effect burst out of an element. The target is measured once, when this function is called. Moving or scrolling afterwards does not move the effect. ## Parameters * `target`[`EffectTarget`](/api/effects/effecttarget/) An element, or a point in page coordinates. * `canvas`optional[`HTMLCanvasElement`](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement) The canvas the effect draws onto, if it doesn’t use the default fullscreen canvas. The origin is then measured from the canvas’ top-left corner, as [CreateEffectOptions.canvas](/api/custom_effects/createeffectoptions/#canvas) expects. ## Returns * [`MeasuredTarget`](/api/custom_effects/measuredtarget/) The origin, and the area for [emitFrom()](/api/custom_effects/emitfrom/). ## Throws * [PartyJSError](/api/utilities/partyjserror/) If called outside a browser, for example during server-side rendering. ## Example ```ts const { origin, area } = measureTarget(button); createEffect({ origin, schedule: { bursts: [{ count: 30 }] }, particleInit: { position: emitFrom(area), // ... }, }); ``` # ParticleInit > Describes the values assigned to a new particle. Describes the values that will be assigned to a particle when it’s spawned. Every field is a [Sampler](/api/samplers/sampler/): either a fixed value, or a function that’s called once for each particle when it spawns, so that particles can differ in appearance. The results become the particle’s initial state (see [Particle](/api/particles/particle/)). After that, behaviors and the simulation steps take over. The values `position`, `velocity`, `orientation` and `angularVelocity` are optional, and default to values producing a particle that starts at the origin, does not move or spin and faces the viewer. ## Example ```ts createEffect({ origin: { x: 200, y: 300 }, schedule: { bursts: [{ count: 30 }] }, particleInit: { position: emitFrom({ type: "disk", radius: 20 }), 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(2, 3), }, }); ``` ## Properties * `angularVelocity`optional[`Sampler`](/api/samplers/sampler/)<[`Vec3`](/api/utilities/vec3/)>default`{ x: 0, y: 0, z: 0 }` How fast the particle spins initially: the direction is the rotation axis (following the right-hand rule) and the length is the speed in degrees per second. Use [randomSpin()](/api/samplers/randomspin/) for a random axis and speed. * `color`[`Sampler`](/api/samplers/sampler/)<`string` | [`Color`](/api/utilities/color-type/)> The initial color of the particle: a CSS color string or a [Color](/api/utilities/color-type/). Strings are converted with [color()](/api/utilities/color/) when the particle spawns, so an invalid color throws at that point rather than when the effect is created. * `lifetime`[`Sampler`](/api/samplers/sampler/)<`number`> How long the particle lives, in seconds. * `orientation`optional[`Sampler`](/api/samplers/sampler/)<[`Quat`](/api/utilities/quat/)>default`{ x: 0, y: 0, z: 0, w: 1 }` The particle’s initial rotation. Use [randomOrientation()](/api/samplers/randomorientation/) for a random one. * `position`optional[`Sampler`](/api/samplers/sampler/)<[`Vec3`](/api/utilities/vec3/)>default`{ x: 0, y: 0, z: 0 }` Where the particle spawns, in pixels from the effect’s origin, in particle space so +y points upwards. Use [emitFrom()](/api/custom_effects/emitfrom/) to spawn particles from an area. * `shape`[`Sampler`](/api/samplers/sampler/)<[`ParticleShape`](/api/particles/particleshape/)> The shape the particle is drawn as. Use [pick()](/api/samplers/pick/) to mix several shapes in the effect. * `size`[`Sampler`](/api/samplers/sampler/)<`number`> The particle’s initial size, in pixels. * `velocity`optional[`Sampler`](/api/samplers/sampler/)<[`Vec3`](/api/utilities/vec3/)>default`{ x: 0, y: 0, z: 0 }` The particle’s starting velocity, in px/s. Use [cone()](/api/samplers/cone/) to emit particles in a direction with some spread. # RectEmissionShape > A rectangular area that particles spawn from. A filled rectangle that particles spawn from, with every point inside it equally likely. Set `width` or `height` to 0 to emit particles from a line. ## Properties * `center`optional[`Vec2`](/api/utilities/vec2/)default`{ x: 0, y: 0 }` The center of the rectangle, in pixels from the origin. * `height``number` The height of the rectangle, in pixels. * * `type``"rect"` * `width``number` The width of the rectangle, in pixels. # BaseEffectOptions > Shared options for effects. extended by [`ConfettiOptions`](/api/effects/confettioptions/), [`CreateEffectOptions`](/api/custom_effects/createeffectoptions/), [`SparklesOptions`](/api/effects/sparklesoptions/) Shared options for built-in and custom effects. ## Properties * `canvas`optional[`HTMLCanvasElement`](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement) A canvas to draw onto. If none is provided, party.js draws onto a fullscreen canvas it shares between all effects, and removes it once no effect is using it anymore. If provided, positions are measured from the canvas’ top-left corner: the built-in effects measure their target relative to it, and a custom effect’s origin is given in its coordinates (see [measureTarget()](/api/custom_effects/measuretarget/)). * `reducedMotion`optional[`ReducedMotion`](/api/effects/reducedmotion/) What the effect does when the user has asked their system for reduced motion. A skipped effect draws nothing, and the `finished` promise on the effect handle resolves as “completed” after `createEffect()` returns, unless you stop the effect immediately. See [ReducedMotion](/api/effects/reducedmotion/) for more information. Without this option, the default set with [setDefaultReducedMotion()](/api/effects/setdefaultreducedmotion/) is used, which is `"skip"` unless you changed it. * `seed`optional`number` A seed for the effect’s random number generator. The same seed with the same options produces the same visuals each time. Without one, a random seed is generated and every run of the effect looks different. # confetti() > Emits a burst of confetti. ```ts function confetti(target: EffectTarget, options?: ConfettiOptions): Effect; ``` Fires a burst of confetti in a cone, upwards by default, from the specified target. The confetti shoots out of the middle of the target, fast and mostly along `angle`. Drag slows it down within a fraction of a second, and it then flutters down slowly like paper, swaying as it tumbles. It grows to its full size over its first 0.03 seconds, fades out over its last second, and is lit with a glossy sheen (`peak: 1.5`). ## Parameters * `target`[`EffectTarget`](/api/effects/effecttarget/) The target the confetti bursts out of. Its position and size are read once, when the effect starts. * `options`optional[`ConfettiOptions`](/api/effects/confettioptions/) Overrides of the default options. See [ConfettiOptions](/api/effects/confettioptions/) for all fields. ## Returns * [`Effect`](/api/effects/effect/) A handle to the running effect. ## Example ```ts button.addEventListener("click", () => confetti(button, { spread: 70 })); ``` # ConfettiOptions > Customization of the built-in confetti effect. extends [`BaseEffectOptions`](/api/effects/baseeffectoptions/) Options for [confetti()](/api/effects/confetti/). ## Properties * `angle`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`90` The angle at which the confetti is emitted, measured counter-clockwise from +x in degrees in particle space, so 0 points right and 90 points up. Sampled once when the effect starts, so all confetti shares the value. * `canvas`optional[`HTMLCanvasElement`](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement) A canvas to draw onto. If none is provided, party.js draws onto a fullscreen canvas it shares between all effects, and removes it once no effect is using it anymore. If provided, positions are measured from the canvas’ top-left corner: the built-in effects measure their target relative to it, and a custom effect’s origin is given in its coordinates (see [measureTarget()](/api/custom_effects/measuretarget/)). * `colors`optional`string`\[] | [`Sampler`](/api/samplers/sampler/)<`string` | [`Color`](/api/utilities/color-type/)>default`randomHue({ l: 0.65, c: 0.15 })` The colors that the confetti can take on. If an array of color strings is given, they are converted to [Color](/api/utilities/color-type/) objects via [color()](/api/utilities/color/), and a random one will be picked for each confetti. Otherwise, the sampler is evaluated for each piece of confetti. * `count`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(15, 30)` How many pieces of confetti are emitted simultaneously at the start of the effect. Sampled once and rounded to the nearest integer. * `drag`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(130, 220)` The speed at which falling confetti stops accelerating, in px/s, where drag balances gravity. Lower values make confetti drift down more slowly, and also keep it from flying as far. Unlike the [drag()](/api/behaviors/drag/) behavior, this is a speed, not a rate. Sampled for each piece of confetti, so a range lets the cloud spread out as it falls. * `gravity`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`800` The strength of gravity affecting the confetti, in px/s². Sampled once when the effect starts, so all confetti shares the value. * `lifetime`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(2, 4)` The lifetime of the confetti, in seconds. Sampled for each piece of confetti. * `reducedMotion`optional[`ReducedMotion`](/api/effects/reducedmotion/) What the effect does when the user has asked their system for reduced motion. A skipped effect draws nothing, and the `finished` promise on the effect handle resolves as “completed” after `createEffect()` returns, unless you stop the effect immediately. See [ReducedMotion](/api/effects/reducedmotion/) for more information. Without this option, the default set with [setDefaultReducedMotion()](/api/effects/setdefaultreducedmotion/) is used, which is `"skip"` unless you changed it. * `seed`optional`number` A seed for the effect’s random number generator. The same seed with the same options produces the same visuals each time. Without one, a random seed is generated and every run of the effect looks different. * `shapes`optional[`Sampler`](/api/samplers/sampler/)<[`ParticleShape`](/api/particles/particleshape/)> | [`ParticleShape`](/api/particles/particleshape/)\[]default`[{ type: "circle" }, { type: "square", cornerRadius: 0.2 }, { type: "square", aspectRatio: 0.2, cornerRadius: 0.05 }]` The shapes that the confetti can take on. If any array of shapes is given, a random one will be picked for each confetti. Otherwise, the sampler is evaluated for each piece of confetti. * `size`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(6, 16)` The initial size of the confetti, in pixels. Sampled for each piece of confetti. * `spread`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`50` How much a confetti’s emission angle may differ from `angle`, in degrees, in either direction. Most confetti flies close to `angle`, and becomes rarer and slower towards the edges of the cone, so the burst shoots out as a jet rather than spraying evenly. Sampled once when the effect starts, so all confetti shares the value. * `startVelocity`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(800, 1500)` How fast confetti starts out, in px/s. Its direction comes from `angle` and `spread`, and confetti towards the edges of the cone starts out up to 45% slower. Drag slows the confetti down quickly, so it travels roughly `startVelocity * drag / gravity` pixels before it starts to fall. Sampled for each piece of confetti. # Effect > A handle to control a running effect. A handle to a running effect, returned by [createEffect()](/api/custom_effects/createeffect/) and the built-in effects, such as [confetti()](/api/effects/confetti/). An effect starts as soon as it’s created, and ends by itself once its schedule is finished and the last particle has expired (i.e. died). You can use this handle to pause it, to let it wind down early with [end()](/api/effects/effect/#end), or to stop it right away with [stop()](/api/effects/effect/#stop). ## Example ```ts const effect = confetti(button); effect.pause(); effect.resume(); effect.stop(); // removes the particles right away ``` ## Properties * `finished`readonly[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EffectResult`](/api/effects/effectresult/)> Settles once the effect is over: with `"completed"` when it ended by itself, including after [end()](/api/effects/effect/#end), or with `"stopped"` when it ended early, because [stop()](/api/effects/effect/#stop) was called or it threw while running. Never rejects. ## Methods ### end() ```ts end(): void; ``` Stops the effect from emitting new particles, and lets the ones that are already alive finish their lifetime. The effect then ends by itself, and the `finished` promise resolves as `"completed"`. Useful to turn off an effect that runs forever, like a stream with `loops: Infinity`. On a paused effect, the remaining particles stay frozen until it’s resumed. Calling [stop()](/api/effects/effect/#stop) afterwards still removes them right away. Calling it again, or after the effect has ended, has no effect. ### pause() ```ts pause(): void; ``` Freezes the effect: particles stop moving and stay visible where they are. Calling it while already paused has no effect. ### resume() ```ts resume(): void; ``` Continues a paused effect from where it was paused. The time spent paused is skipped, so particles do not jump ahead. Does nothing if the effect isn’t paused or has already ended. ### stop() ```ts stop(): void; ``` Ends the effect immediately and removes its particles. The `finished` promise resolves as `"stopped"`, and the effect can’t be resumed afterwards. Calling it again has no effect. The canvas the effect was drawn on is removed (or, if you provided it, cleared) once no other effect is drawing on it. To let the particles finish their lifetime instead, use [end()](/api/effects/effect/#end). # EffectResult > The result of a completed effect. ```ts type EffectResult = "completed" | "stopped"; ``` The result of a completed effect, either `"completed"` if it ended by itself or `"stopped"` if it ended early. An effect that was told to wind down with [end()](/api/effects/effect/#end) also ends by itself, once its last particle has expired, so its result is `"completed"` too. An effect that is skipped due to reduced motion will still have `"completed"` as its result. # EffectTarget > An element or point that an effect bursts out of. ```ts type EffectTarget = HTMLElement | Vec2; ``` What an effect bursts out of: an element on the page, or a point. For an element, the built-in effects burst out of a small area in its middle, which grows with the element’s size. For a point, they spawn exactly there, in page coordinates, i.e. in pixels from the top-left corner of the document, with +y pointing down. Either way, the position is read only once, when the effect starts; moving or scrolling afterwards does not move the effect. ## Example ```ts confetti(document.querySelector("#submit")!); confetti({ x: event.pageX, y: event.pageY }); ``` # ReducedMotion > What an effect does when the user prefers reduced motion. see [MDN: prefers-reduced-motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) ```ts type ReducedMotion = "skip" | "play"; ``` What an effect does when the user has asked their system for reduced motion, through the `prefers-reduced-motion` media query: * `"skip"`: the effect doesn’t play and draws nothing. The `finished` promise on the effect handle will still resolve as “completed”. * `"play"`: the effect plays as usual. The user’s preference is read once, when the effect starts. Changing it while an effect is running doesn’t affect that effect. Particle effects are usually decoration, so party.js skips them by default. Only use `"play"` when the particles carry information the user would otherwise miss, or when the user has explicitly asked to see them, for example through a setting on your site. # setDefaultReducedMotion() > Sets the default way of handling reduced motion. ```ts function setDefaultReducedMotion(mode: ReducedMotion): void; ``` Sets what effects do by default when the user has asked their system for reduced motion. Effects can override this behavior with their `reducedMotion` option. Useful when your site has its own motion setting that should take precedence. ## Parameters * `mode`[`ReducedMotion`](/api/effects/reducedmotion/) What effects started afterwards do when the user prefers reduced motion. ## Example ```ts setDefaultReducedMotion("play"); // This will produce confetti regardless of whether reduced motion is enabled confetti(button); ``` # sparkles() > Bursts twinkling golden sparkles out in all directions. ```ts function sparkles(target: EffectTarget, options?: SparklesOptions): Effect; ``` Bursts twinkling, four-pointed stars, golden by default, out of the specified target, in all directions. The sparkles appear in four quick bursts from the middle of the target, each spread evenly around it. They shoot outwards, slow down quickly and hover, settling slightly downwards while they turn slowly. Occasionally each sparkle catches the light: it briefly grows and flashes towards white, see [twinkle()](/api/behaviors/twinkle/). Most sparkles are small, with a few big ones among them. They pop in almost instantly and shrink away over their last quarter of a second. ## Parameters * `target`[`EffectTarget`](/api/effects/effecttarget/) The target the sparkles burst out of. Its position and size are read once, when the effect starts. * `options`optional[`SparklesOptions`](/api/effects/sparklesoptions/) Overrides of the default options. See [SparklesOptions](/api/effects/sparklesoptions/) for all fields. ## Returns * [`Effect`](/api/effects/effect/) A handle to the running effect. ## Example ```ts button.addEventListener("click", () => sparkles(button, { count: 12 })); ``` # SparklesOptions > How many sparkles to emit, and their color, size, speed and lifetime. extends [`BaseEffectOptions`](/api/effects/baseeffectoptions/) Options for [sparkles()](/api/effects/sparkles/). ## Properties * `canvas`optional[`HTMLCanvasElement`](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement) A canvas to draw onto. If none is provided, party.js draws onto a fullscreen canvas it shares between all effects, and removes it once no effect is using it anymore. If provided, positions are measured from the canvas’ top-left corner: the built-in effects measure their target relative to it, and a custom effect’s origin is given in its coordinates (see [measureTarget()](/api/custom_effects/measuretarget/)). * `colors`optional`string`\[] | [`Sampler`](/api/samplers/sampler/)<`string` | [`Color`](/api/utilities/color-type/)>default`gradient(["oklch(0.7 0.15 70)", "oklch(0.95 0.15 70)"])` The colors the sparkles can take on. An array of color strings is converted with [color()](/api/utilities/color/) right away, and a random one is picked for each sparkle. A sampler is evaluated for each sparkle instead. Sparkles aren’t affected by lighting, so their colors appear exactly as given, except while they glint. * `count`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(20, 40)` How many sparkles are emitted in total. They’re split into four quick bursts over the first 0.3 seconds, so the sparkles don’t all appear at once. Sampled once, and rounded to the nearest integer. * `lifetime`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(0.7, 1.4)` How long the sparkles live, in seconds. Sampled for each sparkle. * `reducedMotion`optional[`ReducedMotion`](/api/effects/reducedmotion/) What the effect does when the user has asked their system for reduced motion. A skipped effect draws nothing, and the `finished` promise on the effect handle resolves as “completed” after `createEffect()` returns, unless you stop the effect immediately. See [ReducedMotion](/api/effects/reducedmotion/) for more information. Without this option, the default set with [setDefaultReducedMotion()](/api/effects/setdefaultreducedmotion/) is used, which is `"skip"` unless you changed it. * `seed`optional`number` A seed for the effect’s random number generator. The same seed with the same options produces the same visuals each time. Without one, a random seed is generated and every run of the effect looks different. * `size`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`24` The size of the largest sparkles, in pixels. Most sparkles are smaller: each one is scaled down by a random factor between 0.2 and 1, with small factors being far more likely, so a few big sparkles stand out among many small ones. Sampled for each sparkle. * `startVelocity`optional[`Sampler`](/api/samplers/sampler/)<`number`>default`range(250, 480)` How fast sparkles burst outwards, in px/s. Drag slows them down quickly, after which they hover and settle. Sampled for each sparkle. # CircleShape > Draws a particle as a circle. A circular shape, centered at (0, 0) with a radius of 0.5. ## Properties * `type``"circle"` # CustomShape > A custom draw instruction for a particle. A shape drawn by a custom function, for anything a [Path2D](https://developer.mozilla.org/docs/Web/API/Path2D) cannot express, such as text, images or gradients. The function is called once per particle on every frame. Before it is called, the context is transformed into shape space (centered at (0, 0), with +y pointing down, rotated according to the particle’s `orientation`, with 1 unit being equal to the particle’s size) and `fillStyle` is set to the particle’s (lit) color. The function also receives the particle being drawn, so the drawing can depend on it. You are free to modify any context state, since it is saved and restored around each call. Nothing will be drawn unless your function does so, for example via `ctx.fill()`. If the shape can be built using a [Path2D](https://developer.mozilla.org/docs/Web/API/Path2D), it is recommended to use [PathShape](/api/particles/pathshape/) instead. ## Example ```ts const ring: CustomShape = { type: "custom", draw(ctx, particle) { const progress = particle.age / particle.lifetime; ctx.strokeStyle = ctx.fillStyle; ctx.lineWidth = 0.2 * (1 - progress); ctx.beginPath(); ctx.arc(0, 0, 0.4, 0, 2 * Math.PI); ctx.stroke(); }, }; ``` ## Properties * `draw`(`ctx`: [`CanvasRenderingContext2D`](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D), `particle`: [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)<[`Particle`](/api/particles/particle/)>) => `void` Draws the particle, in shape space. * `type``"custom"` # ImageShape > Draws a particle as an image. A picture drawn at its own aspect ratio with its longer side filling the 1x1 box. Either pass a URL or anything the canvas can draw, like an ``, `` or `ImageBitmap`. Particles whose image hasn’t loaded yet aren’t drawn, and appear once it has. An image that fails to load is reported once, in the console. An image keeps its own colors: it fades out with the particle’s opacity, but isn’t tinted by its color or lit. ## Example ```ts confetti(button, { shapes: [{ type: "image", image: "/logo.png" }] }); ``` ## Properties * `image``string` | `CanvasImageSource` A URL to load the image from, or anything the canvas can draw. Loading only starts when the first particle spawns, so a large image may not show up in the first effect. To show it right away, preload it, for example with ``, or pass an `` that has already loaded. An SVG passed as an `` needs a `width` and `height`. * `type``"image"` # Particle > The state of a single particle. The state of a single particle while it is alive. Particles live in particle space, measured in pixels from the effect’s origin: +x points right, +y points up and +z points out of the screen towards the viewer. Particles are drawn without perspective, so the z-axis only matters for directions, not positions. On every simulation step, the particle’s `age` advances first. If the particle is still alive, the behaviors run in the order they are listed in the effect. Then the particle is moved by `velocity` and rotated by `angularVelocity`. A particle is removed (i.e. it dies) once its `age` reaches its `lifetime`. Each particle has its own copies of its vectors, color and shape, so behaviors can change them in place or replace them. The only exception is the `path` of a [PathShape](/api/particles/pathshape/), which is shared with other particles possessing the same shape, so it should be replaced rather than modified. ## Properties * `age``number` How long the particle has been alive, in seconds. * `angularVelocity`[`Vec3`](/api/utilities/vec3/) How fast the particle spins. The direction is the rotation axis (following the right-hand rule), and the length is the speed in degrees per second. * `color`[`Color`](/api/utilities/color-type/) The particle’s color, before lighting is applied. * `lifetime``number` How long the particle lives, in seconds. It’s removed (i.e. it dies) once `age` reaches this value. * `orientation`[`Quat`](/api/utilities/quat/) How the particle is rotated. With no rotation, the shape faces the viewer and is drawn exactly as its shape defines. * `position`[`Vec3`](/api/utilities/vec3/) Where the particle is, in pixels from the effect’s origin, in particle space. * `shape`[`ParticleShape`](/api/particles/particleshape/) The shape the particle is drawn as. * `size``number` The particle’s size, in pixels. Its shape’s 1x1 box is scaled to this size. * `velocity`[`Vec3`](/api/utilities/vec3/) How fast the particle moves, in px/s. Applied to `position` on every step, after the behaviors have run. # ParticleShape > The shape a particle is drawn as. ```ts type ParticleShape = | SquareShape | CircleShape | StarShape | PolygonShape | PathShape | TextShape | ImageShape | CustomShape; ``` Controls the way a particle is drawn onto the canvas. Every shape is drawn in the same space: centered at (0, 0), fitting inside a 1x1 box from -0.5 to 0.5, with +y pointing down, as it would on a regular canvas. That box is then scaled to the particle’s `size`, rotated by its `orientation`, and the `fillStyle` is set to its (lit) `color`. Built-in and path shapes are filled with this color, while custom shapes draw themselves. # PathShape > Draws a particle according to a given path. A shape determined by a [Path2D](https://developer.mozilla.org/docs/Web/API/Path2D). The path is expected to fit in a 1x1 box centered at (0, 0), oriented to have +y pointing down. A supplied [Path2D](https://developer.mozilla.org/docs/Web/API/Path2D) should only be created once, outside of any samplers, to avoid it being created for every particle. ## Properties * * `path`[`Path2D`](https://developer.mozilla.org/docs/Web/API/Path2D) * `type``"path"` # PolygonShape > Draws a particle as a regular polygon. A regular polygonal shape, centered at (0, 0), with a specified number of sides. ## Properties * `sides``number` The number of sides the regular polygon should have, which is expected to be an integer >= 3. * `type``"polygon"` # SquareShape > Draws a particle as a square. A square shape, centered at (0, 0), that can be stretched via an aspect ratio and rounded via a corner radius. ## Properties * `aspectRatio`optional`number`default`1` The ratio of width to height for the square. The longer side will be kept at length 1, so the shape always fills the box in one direction. For example, a value of 0.3 produces a tall, narrow strip. * `cornerRadius`optional`number`default`0` The radius of the corners, in shape units where the longer side is 1. This is expected to be non-negative, and will be clamped if it exceeds half of the width or height of the shape. * `type``"square"` # StarShape > Draws a particle as a regular, pointed star. A regular, pointed star, centered at (0, 0), with a specified number of points. ## Properties * `innerRadius`optional`number`default`0.382` How far the inner corners between the points are from the center, relative to the points themselves, from just above 0 (thin, spiky points) to 1 (no points at all). The default gives the proportions of a classic five-pointed star. * `points`optional`number`default`5` The number of points the star should have, which is expected to be an integer >= 3. * `type``"star"` # TextShape > Draws a particle as text or emoji. A string of text or emoji, rendered optionally with a specified font. ## Properties * `font`optional`string`default`sans-serif` A CSS font family. * `text``string` The text to draw, for example an emoji or glyph like `*`. * `type``"text"` # cone() > Creates velocities in a direction, with some random spread. ```ts function cone( angle: number, deviation: number, speed: Sampler, ): SamplerFn; ``` Creates a sampler for velocities that point in a direction, with some deviation. Angles are in degrees, measured counter-clockwise from +x in particle space, so 0 points right and 90 points up. The angle is chosen with [spread()](/api/samplers/spread/), so a burst fans out evenly across the cone. A `deviation` of 0 sends every particle in exactly the same direction. ## Parameters * `angle``number` The direction of the cone’s center, in degrees. * `deviation``number` How far a particle’s direction may lie from `angle`, in degrees, in either direction. * `speed`[`Sampler`](/api/samplers/sampler/)<`number`> The speed, in px/s. Can itself be a sampler. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<[`Vec3`](/api/utilities/vec3/)> ## Example ```ts // Upwards, fanning out 30° to either side, with constant speed. cone(90, 30, 400); // Straight down, at varying speeds. cone(-90, 0, range(60, 120)); ``` # evaluateSampler() > Resolves a sampler to a value. ```ts function evaluateSampler(sampler: Sampler, ctx: SamplerContext): T; ``` Resolves a [Sampler](/api/samplers/sampler/) to a value, by calling it if it is a function, or returning it unchanged if it is a fixed value. This can be useful when writing your own samplers that build on other samplers. ## Type Parameters * `T` ## Parameters * `sampler`[`Sampler`](/api/samplers/sampler/)<`T`> The sampler to resolve. * `ctx`[`SamplerContext`](/api/samplers/samplercontext/) The context to pass on if the `sampler` is a function. ## Returns * `T` The sampled value. ## Example ```ts const doubled = (base: Sampler): SamplerFn => (ctx) => 2 * evaluateSampler(base, ctx); ``` # gradient() > Picks random colors from a gradient. ```ts function gradient( colors: (string | Color)[] | GradientStop[], ): SamplerFn; ``` Creates a sampler that picks a random color from a gradient. Each particle gets a random position along the gradient, with every position being equally likely. This means that the colors appear in the proportions the gradient gives them. Plain colors are spaced evenly, and one can use [stops](/api/samplers/gradientstop/) to give some colors a higher chance than others. ## Parameters * `colors`(`string` | [`Color`](/api/utilities/color-type/))\[] | [`GradientStop`](/api/samplers/gradientstop/)\[] The colors, evenly spaced, or explicit stops. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<[`Color`](/api/utilities/color-type/)> ## Throws * [PartyJSError](/api/utilities/partyjserror/) If no colors or stops are given, if a stop’s offset is outside `[0, 1]`, or if a color string is invalid. # GradientStop > A color at a chosen position along a gradient. A color at a specific position along a gradient, to be used with the [gradient()](/api/samplers/gradient/) sampler when the colors should not be spaced evenly. Because [gradient()](/api/samplers/gradient/) chooses a (uniformly) random position along it for each particle, the spacing of the stops determines how common a color is: the wider the gap between two stops, the more particles get a color that is sampled between those stops. Stops can be listed in any order, and two stops at the same offset create a hard edge instead of a blend. ## Example ```ts // 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" }, ]); ``` ## Properties * `color``string` | [`Color`](/api/utilities/color-type/) The color at this position. Accepts anything [color()](/api/utilities/color/) accepts. * `offset``number` The position of the stop, from 0 (the start of the gradient) to 1 (the end). Values outside this range throw a [PartyJSError](/api/utilities/partyjserror/). # normal() > Picks random numbers that cluster around a mean. see [Wikipedia: Box–Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform) ```ts function normal(mean: number, stdDev: number): SamplerFn; ``` Creates a sampler that picks numbers from a normal (bell curve) distribution: most values land near `mean`, and fewer the further away they are. About 68% fall within one `stdDev` of the mean, about 95% within two and about 99.7% within three. The values have no hard limits, so occasionally one can be produced that’s far from the mean. Prefer [range()](/api/samplers/range/) for properties that must stay within bounds, like a size that cannot be negative. ## Parameters * `mean``number` The value the results cluster around. * `stdDev``number` How widely the results spread around the mean. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<`number`> # pick() > Picks one of several values at random. ```ts function pick(arr: T[], weights?: number[]): SamplerFn; ``` Creates a sampler that picks one of the given values at random, either with equal chances or weighted ones. Weights are relative and don’t need to add up to 1: `[3, 1]` will make the first value three times as likely as the second one. ## Type Parameters * `T` ## Parameters * `arr``T`\[] The values to pick from. * `weights`optional`number`\[] Optional relative chances, one per value. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<`T`> ## Throws * [PartyJSError](/api/utilities/partyjserror/) If `arr` is empty, if the number of weights doesn’t match the number of values, if a weight is negative or if all weights are zero. ## Example ```ts // Mostly circles with an occasional star. pick([{ type: "circle" }, { type: "star" }], [4, 1]); ``` # randomHue() > Picks colors with a random hue. see [oklch.com](https://oklch.com) ```ts function randomHue(options: RandomHueOptions): SamplerFn; ``` Creates a sampler for colors of the same lightness and intensity, with a random hue. Because Oklch is perceptually uniform, all hues come out equally bright, which makes for even, rainbow-like mixes. ## Parameters * `options`[`RandomHueOptions`](/api/samplers/randomhueoptions/) The lightness, chroma and opacity shared by all colors. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<[`Color`](/api/utilities/color-type/)> ## Throws * [PartyJSError](/api/utilities/partyjserror/) If the supplied chroma is negative. ## Example ```ts const color = randomHue({ l: 0.7, c: 0.15 }); ``` # RandomHueOptions > The lightness, chroma and opacity of random-hue colors. Options for [randomHue()](/api/samplers/randomhue/). ## Properties * `alpha`optional`number`default`1` Opacity, from 0 (transparent) to 1 (opaque). * `c``number` Chroma: how intense the colors are, from 0 (gray) upwards. Around 0.1-0.2 gives vivid colors, while very high values cannot be shown on a screen and will be clipped. * `l``number` Lightness, from 0 (black) to 1 (white). # randomOrientation() > Picks a random rotation. see Shoemake, K. (1992). “III.6 - Uniform Random Rotations.” ```ts function randomOrientation(axis?: Readonly): SamplerFn; ``` Creates a sampler for random rotations. If no axis is provided then each orientation is equally likely, otherwise the rotation is only created around the given axis. For example, rotations around +z keep flat shapes facing the viewer, only turning them within the screen plane. ## Parameters * `axis`optional[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)<[`Vec3`](/api/utilities/vec3/)> Optionally, the axis to create the rotation around. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<[`Quat`](/api/utilities/quat/)> # randomSpin() > Picks a random spin axis and speed. see [Wolfram MathWorld: Sphere Point Picking](https://mathworld.wolfram.com/SpherePointPicking.html) ```ts function randomSpin( min: number, max: number, axis?: Readonly, ): SamplerFn; ``` Creates a sampler for spinning in a random direction: a speed between `min` and `max` on a rotation axis. If no axis is provided, a random one is sampled. ## Parameters * `min``number` The slowest spin, in degrees per second. * `max``number` The fastest spin, in degrees per second. * `axis`optional[`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)<[`Vec3`](/api/utilities/vec3/)> Optionally, the axis to create the rotation on. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<[`Vec3`](/api/utilities/vec3/)> # range() > Picks a random number between two bounds. ```ts function range(min: number, max: number): SamplerFn; ``` Creates a sampler to uniformly choose a value between `min` and `max`. ## Parameters * `min``number` The lower bound. * `max``number` The upper bound. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<`number`> ## Example ```ts const size = range(8, 16); ``` # Sampler > A fixed value, or a function that produces one. ```ts type Sampler = T | SamplerFn; ``` Either a fixed value, or a [SamplerFn](/api/samplers/samplerfn/) that produces one. Wherever party.js accepts a sampler, you can pass a plain value that is shared between particles (for example `size: 8`), or a function that is called again for each particle (for example `size: range(4, 12)`). Typically, these functions will be evaluated when the particle spawns. ## Type Parameters * `T` # SamplerContext > Information passed to a sampler function. Information passed to a [SamplerFn](/api/samplers/samplerfn/) each time it is called. ## Properties * `batch`optional`object` When sampling particle properties, multiple particles spawned in one simulation step are batched, in which case this field contains information on the batch. Otherwise this field will be absent. * `batch.index``number` The particle’s position in the batch, starting at 0. * `batch.size``number` How many particles will be spawned at once. * `index``number` A running count. For a particle’s properties, it’s the number of particles the effect has spawned before this one. For a burst’s `count`, it’s the current loop of the [EmissionSchedule](/api/custom_effects/emissionschedule/). * `rng`[`Rng`](/api/utilities/rng/) The effect’s random number generator. Use it instead of `Math.random()` to keep seeded effects reproducible. # SamplerFn > A function that produces a value. ```ts type SamplerFn = (ctx: SamplerContext) => T; ``` A function that produces a value each time it’s called, such as a random size or color. ## Type Parameters * `T` ## Parameters * `ctx`[`SamplerContext`](/api/samplers/samplercontext/) ## Returns * `T` ## Example ```ts // Every particle's size will be a bit larger than the one before. const growing: SamplerFn = (ctx) => 2 + ctx.index * 0.5; ``` # spread() > Picks numbers spread evenly around a center. ```ts function spread(center: number, deviation: number): SamplerFn; ``` Creates a sampler that picks numbers from `center - deviation` to `center + deviation`, spread evenly across each batch of particles. Within a batch (a group of particles spawned in the same simulation step, such as a burst), the range is divided into one equal slice per particle, and each particle gets a random value within its own slice. A burst therefore will always cover the whole range evenly, without the clumps and gaps that truly independent random values could produce. A particle spawned on its own gets a random value from the whole range. ## Parameters * `center``number` The middle of the range. * `deviation``number` How far values may lie from the center, in either direction. ## Returns * [`SamplerFn`](/api/samplers/samplerfn/)<`number`> # color() > Converts a CSS color string to an Oklab color. ```ts function color(input: string | Color): Color; ``` Converts a CSS color string to a [Color](/api/utilities/color-type/). Accepts hex colors (`#f00`, `#ff5a5f`, `#ff000080`) and the `rgb()`/`rgba()`, `hsl()`/`hsla()`, `oklab()` and `oklch()` functions. A [Color](/api/utilities/color-type/) passed in is returned unchanged. Note that named colors are **not** supported, to minimize bundle size. In particular, `transparent` is not a valid color input. ## Parameters * `input``string` | [`Color`](/api/utilities/color-type/) A CSS color string, or an existing color. ## Returns * [`Color`](/api/utilities/color-type/) The Oklab color. ## Throws * [PartyJSError](/api/utilities/partyjserror/) If the string isn’t a supported color. ## Example ```ts const cornflowerblue = color("#6495ed"); ``` # Color > A color in the Oklab color space. see [Björn Ottosson: A perceptual color space](https://bottosson.github.io/posts/oklab/) A color in the Oklab color space, which party.js uses internally because it is perceptually uniform. Gradients blend evenly, and lighting changes brightness without shifting the hue. You rarely need to build one by hand: You can pass a CSS color string to [color()](/api/utilities/color/), or anywhere that accepts colors, instead. ## Properties * `a``number` Position on the green (negative) to red (positive) axis, about -0.3 to 0.3 for screen colors. * `alpha``number` Opacity, from 0 (transparent) to 1 (opaque). * `b``number` Position on the blue (negative) to yellow (positive) axis, about -0.3 to 0.3 for screen colors. * `l``number` Perceived lightness, from 0 (black) to 1 (white). # PartyJSError > The error party.js throws for invalid input. extends [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) The error party.js throws when it’s given invalid input, for example a color string it cannot parse. Its error message is prefixed with `[party-js]`. ## Example ```ts try { confetti(button, { colors: gradient([]) }); } catch (error) { if (error instanceof PartyJSError) showHint(error.message); else throw error; } ``` ## Constructor ```ts new PartyJSError(message: string); ``` #### Parameters * `message``string` # Quat > A 3D rotation, stored as a unit quaternion. A rotation in 3D, stored as a unit quaternion. Used for a particle’s orientation. You rarely need to build one by hand: [randomOrientation()](/api/samplers/randomorientation/) covers the common case of generating a random initial rotation. ## Properties * * `w``number` * `x``number` * `y``number` * `z``number` # Rng > A source of random numbers from 0 to 1. ```ts type Rng = () => number; ``` A function that returns a pseudo-random number from 0 (inclusive) to 1 (exclusive), like [Math.random()](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/random). Every effect has one, created from its `seed`, to ensure that seeded effects play out the same way every time. Samplers and behaviors receive it as `ctx.rng`. It is recommended that you use it instead of `Math.random()` in your own samplers and behaviors, so they stay reproducible too. ## Returns * `number` A pseudo-random number from 0 (inclusive) to 1 (exclusive). # Vec2 > A 2D vector. A vector in 2D space. ## Properties * * `x``number` * `y``number` # Vec3 > A 3D vector. A vector in 3D space, usually used to represent a particle’s position or velocity. ## Properties * * `x``number` * `y``number` * `z``number`