Creative Coding From Zero · Episode 03
Particle Systems
Particle Systems is Episode 03 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Every spark off a campfire, every snowfall in a game, every firework finale, every cursor trail and explosion and puff of dust you have ever seen on a screen is the same little program. A particle is just a dot with a position, a velocity, and a lifetime. You make a bunch of them, and once per frame you do three things: move each one, age each one, draw each one. That's it. That ~20-line loop is the single most reused pattern in all of creative coding, and once it's in your hands you start seeing it everywhere.
The demo below starts as a calm fountain — particles thrown upward, arcing over, raining back down in color. With the six-stage selector and a couple of sliders you'll walk it all the way up to fireworks: shells that climb, pause, and burst into a shower of fading sparks. Same loop the whole way. Drag the sliders, hit regenerate, and watch the same handful of rules produce a screensaver you'd actually leave running.
What you're looking at
One fixed array of particles — a pool — sits in memory the whole time. An emitter at the bottom-center keeps grabbing dead particles from the pool, setting a fresh position and an upward-ish velocity, and letting them go. Each frame, gravity pulls every live particle down, the particle drifts, its lifetime ticks toward zero, and its color and opacity fade with its age. When a particle's life hits zero it isn't deleted — it's just marked dead and handed back to the emitter to be reused. Nothing is ever allocated after the first frame. That recycling is the entire trick to keeping thousands of particles at 60fps, and it's why the fps counter stays pinned no matter how hard you push the emission slider.
The six stages are the same system with more of its parts switched on, mapped 1:1 to the sections below. Stage 1 is a single particle so you can see the physics naked. Stage 6 is hundreds of particles organized into bursting shells. Everything in between is one more rule.
Stage 1 — One particle
The whole idea, with a population of one. A particle gets a position and a velocity, and every frame we add gravity to the velocity and the velocity to the position. The result is the oldest animation in the book: a thing thrown up and to the side traces a parabola, slows at the top, and accelerates back down. When it falls off the bottom we relaunch it. Watch the arc. There is no special "arc" code — the parabola falls out of "add a little downward speed every frame." That emergent curve is the seed of everything else here.
Stage 2 — An emitter
Now instead of one particle we spawn a steady stream from a single point. The emission slider sets how many we release per second. Each new particle gets a slightly different launch angle and speed — that random scatter is what the spread slider controls — so the stream fans out into a spray instead of a single line. This is the moment a "particle" becomes a "particle system": a source that keeps producing, each child living its own little parabola. Notice there's no fade yet, so the screen slowly fills with hard dots. That's the next problem.
Stage 3 — Lifetime + fade
Hard dots that never leave will, given a minute, cover the canvas and crush your
frame rate. The fix is the third number every particle carries: a lifetime.
Each frame we subtract dt from it; when it reaches zero the particle dies.
The lifetime slider sets how long they last. Two things happen at once now. First, the
population stabilizes — particles die as fast as they're born, so the pool reaches a
steady state instead of growing forever. Second, we tie each particle's opacity
to life / maxLife, so it fades smoothly to nothing instead of blinking out.
Smooth birth, smooth death, constant cost. This is the heart of the episode.
Stage 4 — Forces
Gravity is just one force — a constant downward acceleration we add to velocity every frame. Once you see it that way, you can add others the exact same way. This stage layers on a steady wind pushing sideways and a touch of drag that scales velocity down a hair each frame, like air resistance. Crank the gravity slider and the stream slams down; the wind shears the whole spray to one side; drag rounds off the sharp ballistic arcs into softer, floatier paths. Three one-line forces, summed into one acceleration, completely reshape the motion. This is how you'd do smoke, rain in a storm, sparks in a draft — same loop, different forces.
Stage 5 — Fountain
Tune those same knobs for beauty instead of demonstration and you get a fountain: a tight upward jet, a sensible lifetime, color mapped to age so each particle glows hot at birth and cools as it falls. We draw onto a faintly persistent canvas instead of clearing it hard, which leaves gentle motion trails and turns discrete dots into liquid streaks. This is the default stage — pretty, calm, and a genuinely nice thing to leave running. Every slider still does what it did before; play with spread and lifetime to go from a needle-thin spout to a wide, lazy spill.
Stage 6 — Fireworks
The payoff, and it's startling how little new code it takes. Instead of a continuous
emitter we periodically launch a shell: a single particle fired upward.
When a shell's lifetime runs out — at the top of its arc — we don't just kill it, we call
a burst() that emits a ring of dozens of spark particles from its
position, each with its own outward velocity, color, and short life. Gravity and fade do
the rest: the sparks spray out, slow, droop, and dim into the dark. Periodic shells,
explode-on-death, gravity, fade. Four ideas you already have, arranged into the most
satisfying ten seconds in this whole series. Watch the fps — even at full bursts it
barely moves, because every spark is a recycled corpse from the pool, not a new
allocation.
How the code works
Four pieces carry the entire system. We'll build them in the order they run: the pool that holds particles, then emit / update / draw — the three verbs of the per-frame loop.
1 · The pre-allocated pool (and why you must cap it)
The number-one way to kill a particle demo is to push() a new object
every frame and never remove the dead ones. The array grows without bound, the garbage
collector thrashes, and the frame rate falls off a cliff. So we never grow at runtime.
We allocate one fixed array of plain particle objects up front — the
pool — and reuse its slots forever. A particle is "dead" simply when
its life <= 0. To find a free slot to emit into, we sweep a rotating
recycle cursor around the ring until we hit a dead one (or give up if the
pool is momentarily full — capping is a feature, not a failure):
// One fixed pool. Allocated ONCE. Never grows. This is the whole trick.
const MAX = 4000;
const pool = [];
for (let i = 0; i < MAX; i++) {
pool.push({ x:0, y:0, vx:0, vy:0,
life:0, maxLife:1, hue:0, size:2, kind:0 });
}
let recycle = 0; // rotating cursor into the pool
// Find a dead slot to reuse. Returns null if the pool is full — and that's FINE:
// a capped pool that occasionally drops an emission never tanks your fps.
function alloc() {
for (let n = 0; n < MAX; n++) {
const p = pool[recycle];
recycle = (recycle + 1) % MAX; // wrap around the ring
if (p.life <= 0) return p; // found a corpse → reuse it
}
return null; // pool saturated this frame
}
2 · Emit — set position, velocity, life
Emitting is nothing more than grabbing a dead slot and overwriting its fields with
fresh birth values. No new, no allocation — we're stamping new state onto
an old object. A fountain emitter fires mostly upward with a random sideways spread; the
angle and speed jitter is what turns a single jet into a spray. Note every random call
goes through the seeded rnd() so the same seed replays the exact same
show:
// Spawn one fountain particle from (ox,oy). speed/spread come from sliders.
function emit(ox, oy) {
const p = alloc();
if (!p) return; // pool full → silently skip
const ang = -Math.PI / 2 // -90° = straight up
+ (rnd() - 0.5) * spread; // fan out by the spread knob
const spd = 180 + rnd() * 120; // px/sec, with jitter
p.x = ox; p.y = oy;
p.vx = Math.cos(ang) * spd;
p.vy = Math.sin(ang) * spd;
p.maxLife = lifeSec;
p.life = lifeSec; // counts DOWN to 0, then it's dead
p.hue = 30 + rnd() * 30; // warm at birth
p.size = 1.5 + rnd() * 2;
}
3 · Update — the three-line physics, scaled by dt
Here is the loop everything in this episode is built from. For every live particle:
add gravity (and any other forces) to velocity, add velocity to position, subtract
elapsed time from life. Each of those is multiplied by dt, the seconds
since the last frame — without that, the animation runs at different speeds on a 60Hz
laptop and a 144Hz monitor. For fireworks, the only addition is: when a shell's life
expires, call burst() before recycling it.
// The entire simulation. Runs once per frame over the whole pool.
function update(dt) {
for (let i = 0; i < MAX; i++) {
const p = pool[i];
if (p.life <= 0) continue; // skip the dead
p.vy += gravity * dt; // gravity: a downward force
p.vx += wind * dt; // wind: a sideways force
p.vx *= drag; p.vy *= drag; // drag: air resistance
p.x += p.vx * dt; // integrate position
p.y += p.vy * dt;
p.life -= dt; // age it
if (p.life <= 0 && p.kind === SHELL) {
burst(p.x, p.y, p.hue); // explode on death → sparks
}
}
}
4 · Draw — alpha tied to life, plus the burst helper
Drawing is per-particle and dead-simple, but one line matters more than the rest:
alpha = life / maxLife. Tying opacity to remaining life is what makes
particles fade instead of popping out of existence — forget it and you get an
ugly hard blink at the end of every life. We color by age too, so particles cool as
they go. And burst() is just emit in a ring: it's the same
recycle-a-slot move, fired in every direction at once.
// Draw every live particle. alpha = life/maxLife → smooth fade-out.
function draw() {
for (let i = 0; i < MAX; i++) {
const p = pool[i];
if (p.life <= 0) continue;
const t = p.life / p.maxLife; // 1 at birth → 0 at death
ctx.globalAlpha = t; // THE fade. Don't skip this line.
ctx.fillStyle = `hsl(${p.hue}, 100%, ${40 + t * 40}%)`;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = 1; // always reset!
}
// A firework burst: emit a ring of sparks from one point.
function burst(x, y, hue) {
const count = 60;
for (let i = 0; i < count; i++) {
const p = alloc();
if (!p) break; // pool full → stop early, no crash
const a = (i / count) * Math.PI * 2 + rnd() * 0.2;
const s = 40 + rnd() * 160;
p.x = x; p.y = y;
p.vx = Math.cos(a) * s;
p.vy = Math.sin(a) * s;
p.life = p.maxLife = 0.8 + rnd() * 0.8;
p.hue = hue + rnd() * 40 - 20;
p.size = 1 + rnd() * 1.5;
p.kind = SPARK; // sparks don't re-burst
}
}
That's the complete pattern. Pool, emit, update, draw. Read those four blocks again and you'll notice there isn't a single line specific to "fountains" or "fireworks" — just dots with velocity and life. The genre is entirely in how you tune the emit and the forces.
Common pitfalls
- Particle leaks → fps death. The classic. You
push()new particles and never remove the dead ones, so the array grows forever until the page chokes. The cure is structural, not a patch: a fixed-size pool you recycle, with a hard cap. If the cap is hit, drop the emission — a missing spark is invisible; a 4-fps fountain is not. - Per-frame allocation. Even with a cap, calling
{ }/new Particle()every frame makes garbage for the collector to sweep, causing periodic stutters. Allocate the pool once and mutate slots forever. Zero allocation in the hot loop. - Frame-rate-dependent motion. If you do
p.x += p.vxwith nodt, your fountain runs twice as fast on a 120Hz screen as on a 60Hz one. Always scale movement, forces, and aging by the real elapsed seconds. - Alpha not tied to life → hard pops. If a particle is fully
opaque right up until
lifehits zero, it vanishes with an ugly blink. SetglobalAlpha = life / maxLifeso it dissolves. And always resetglobalAlpha = 1afterward, or it leaks into everything else you draw. - Trail vs clear — pick on purpose. A hard
clearRectevery frame gives crisp, separate dots (right for snow). A translucentfillRectover the whole canvas leaves motion trails (right for a fountain or fireworks). Choosing the wrong one is the most common "why does it look off?" — the fountain stage uses trails on purpose; toggle to a stage that clears to feel the difference.
Exercises
- A wind field from noise. Replace the constant
windwith a value sampled from 2D value noise at each particle's position (themakeNoise/fbmhelpers from the series brief). Now the wind swirls — particles get caught in invisible eddies. This is a sneak preview of Episode 04's flow fields, applied to a system you already understand. - Emit from the mouse. Track
mousemoveon the canvas and make the emitter follow the cursor instead of sitting at the bottom-center. Suddenly it's a sparkler you paint with. Bonus: emit faster while the mouse is moving (compute pointer speed between frames) so fast strokes throw more particles. - Smoke trails on the shells. In the fireworks stage, have each
rising shell
emitone tiny, short-lived, low-opacity grey particle every frame as it climbs. The shell now leaves a smoke trail behind it, and the burst feels ten times more like a real firework. Watch your pool cap — trails eat slots fast.
What's next
Episode 04 — Flow Fields. We take the "thousands of cheap agents in a pool" idea you just built and steer every one of them with a field of noise-driven directions. No gravity, no emitter — just particles flowing along invisible currents, leaving long painterly strokes behind them. It's the crown jewel of generative art, the technique behind a thousand gorgeous prints, and it's barely more code than this. The pool you just learned to recycle is exactly the engine it runs on.