Creative Coding From Zero · Episode 04
Flow Fields
Flow Fields is Episode 04 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 .
You've seen this image a thousand times — on album covers, festival posters, the wallpaper that shipped with someone's phone, the cover of a generative-art book. Tens of thousands of fine, swooping lines that all seem to be caught in the same invisible current, like iron filings around a magnet or wind on a weather map. It looks impossibly intricate. It is, in fact, one of the simplest things in this entire series: a grid of angles, and a swarm of dots that follow them.
Here's the promise. By the end of this page you'll understand the single most important technique in generative art — the flow field — and you'll have built one from absolute scratch in raw canvas 2D. Every time you hit Regenerate you get a brand-new, one-of-a-kind composition that has never existed before and never will again, and the Save PNG button turns any of them into a frame-worthy poster on your wall. No two seeds are alike. Drag the demo to stage 6, find a seed you love, and download it.
Six stages, one system. The select box walks you from "what even is a field" to a finished poster, and at every step the picture is visibly a different state of the same machine. Let's build it.
What you're looking at
There are exactly three moving parts, and you already understand two of them from earlier episodes:
- A flow field: an invisible grid laid over the canvas where every point stores a direction — an angle. We don't store a giant array; we compute the angle on demand from Episode 03's value noise. Smooth noise in, smooth swirling directions out.
- A swarm of agents: little particles, each just an
(x, y)position. Every frame, each agent asks the field "which way here?" and takes one small step that direction, drawing a short segment as it goes. - Persistence: we don't wipe the canvas between frames. The segments pile up. Thousands of agents tracing the same current for a few hundred frames is what turns a scribble into those dense, silky ribbons.
That's the whole trick. Noise gives the field its organic curl, the agents make it visible, and persistence accumulates their paths into art. Everything below is just those three ideas, turned up one dial at a time.
Stage 1 — The field, made visible
Before anything moves, let's see the field. A flow field assigns an angle to every point in the plane. The cleanest way to get a smooth, swirling angle is to take fractal noise — which returns a smooth value that drifts gently as you move across the plane — and stretch its range out to a full turn:
// The heart of the whole episode. One line.
function fieldAngle(x, y) {
// fbm returns ~[-1,1]; map it to a full turn of radians.
return fbm(noise, x * scale, y * scale) * TAU; // TAU = 2π
}
To draw it, we sample that angle on a coarse grid and draw a tiny arrow at each cell
pointing along it. The scale slider is the single most important knob in
the whole demo: it sets how fast the angle changes as you move across the canvas.
Small scale → the angle barely changes → broad, lazy currents. Large scale → it churns
→ tight, chaotic turbulence. Drag the field scale slider in stage 1 and
watch the arrow field reorganize itself in real time.
A flow field is just a function from(x, y)to an angle. Noise is how we get one that's smooth and organic instead of random and jagged. Swap the noise for a formula —atan2(y, x), say — and you'd get a perfect vortex. The field is the art direction; the agents are the brush.
Stage 2 — One agent, one streamline
Now release a single dot into the field and let it go with the flow. Each frame it looks up the angle beneath its feet, takes one small step in that direction, and draws a line segment from where it was to where it is now. Repeat. The path it traces is called a streamline — the trajectory you'd follow if you were a leaf on that current:
// b) The agent update + segment draw — the core loop body.
const a = fieldAngle(agent.x, agent.y); // which way here?
const px = agent.x, py = agent.y; // remember where we were
agent.x += Math.cos(a) * step; // step along the angle…
agent.y += Math.sin(a) * step; // …in x and y
ctx.beginPath();
ctx.moveTo(px, py);
ctx.lineTo(agent.x, agent.y); // draw the segment we just traveled
ctx.stroke();
That cos/sin pair is how an angle becomes
motion — the exact thing Episode 05 is about. For now just notice what the
single agent does: it never crosses itself, it banks smoothly through the noise, and it
looks exactly like a particle in a wind tunnel. One dot, and you can already read the
shape of the field.
Stage 3 — Many agents
One streamline is pretty. A thousand is a structure. We scatter N agents
at seeded-random positions and step them all every frame, each drawing its own thin
line. Because they all obey the same field, neighbours flow in near-parallel — and the
field's swirls show up as whole bundles of lines fanning, merging, and splitting:
// Spawn the swarm — seeded so a given seed reproduces the piece.
const rnd = mulberry32(seed);
const agents = [];
for (let i = 0; i < N; i++) {
agents.push({ x: rnd() * W, y: rnd() * H }); // random start, deterministic
}
Crank the agents slider — it goes to 5,000. Notice the demo still holds 60fps: drawing a few thousand one-segment lines per frame is nothing for canvas 2D. The cost of a flow field isn't the agent count; it's how many frames you let it accumulate, which is free.
Stage 4 — Ink build-up (the whole point)
Here is the stage that separates "I drew some lines" from "I made the poster." In stages 1–3 the demo quietly clears the canvas each frame so you can see the live motion. Stage 4 stops clearing. Every segment every agent has ever drawn stays on the canvas. The ink builds. Watch the empty black fill in over a few seconds with dense, layered ribbons — that accumulation is the artwork:
// c) PERSISTENCE — the single most important decision in this episode.
function frame() {
// DO NOT do this in poster mode:
// ctx.clearRect(0, 0, W, H); ← erases the painting every frame
// Optional living version: a *barely* translucent veil that slowly
// fades old ink so the piece breathes instead of saturating.
// ctx.fillStyle = 'rgba(10,10,10,0.012)'; ctx.fillRect(0,0,W,H);
for (const ag of agents) stepAndDraw(ag); // just keep painting
requestAnimationFrame(frame);
}
This is the #1 thing beginners get wrong. Their flow field "doesn't
work" — they see a thin layer of lines that never builds up — and the bug is always the
same reflexive clearRect at the top of the loop, a habit from every other
animation. In a flow field the canvas is your accumulation buffer. Clearing it
throws away the painting sixty times a second. Persistence isn't a side effect here; it's
the medium.
The commented-out fillRect is the subtle middle path: instead of a hard
clear, paint a near-invisible dark rectangle over everything each frame. Old ink fades
extremely slowly, new ink lands on top, and the piece never fully saturates — a
"living" poster that keeps reorganizing. Keep that alpha tiny (≈0.01–0.02) or it eats
your ribbons alive.
Stage 5 — Color from the field
Black ink on black is dramatic, but the iconic version is in color. We reach for the
cosine palette from earlier and feed it a value
that varies smoothly across the piece, so neighbouring streamlines get neighbouring
hues and the whole thing reads as one harmonious gradient instead of confetti. A great
choice is the field angle itself, normalized to [0,1]:
// d) Palette mapping — color each segment by the local field angle.
const a = fieldAngle(ag.x, ag.y);
const t = (a / TAU) % 1; // angle → [0,1]
ctx.strokeStyle = cosPalette(t, A, B, C, D); // vivid, harmonious
ctx.globalAlpha = 0.06; // LOW — let ink build gradually
Two dials make or break the look. The palette select swaps the
cosine coefficients (Ember, Ice, Acid, Mono). And globalAlpha stays
deliberately low — around 0.05–0.08. At full opacity the first pass slams every
pixel to solid color and you lose all the gorgeous layering. Low alpha is what lets a
hundred faint passes stack into deep, glowing density. Patience, in a number.
Stage 6 — Poster mode
Everything together, dialled up: thousands of agents, a tuned scale, a chosen palette, low alpha, full persistence, and a seed. The result is a finished piece. When you find one you love, exporting it is two lines — canvas already is a PNG, you just ask for it as a data URL and click an invisible link:
// d, continued) Save the canvas as a downloadable PNG.
const url = canvas.toDataURL('image/png'); // the whole canvas, encoded
const a = document.createElement('a');
a.href = url;
a.download = 'flow-field-' + seed + '.png'; // seed in the filename!
a.click(); // triggers the browser download
Naming the file after the seed is a small thing that matters: the seed is the artwork. Two people running this code with the same seed get the identical poster, pixel for pixel — that's the whole point of the seeded RNG from Episode 02. Hit Regenerate to roll a fresh seed, let it paint for a few seconds, and when the composition sings, Save PNG. You just made original art.
How the code works, end to end
Stripped to its skeleton, the entire engine fits in your head. Build a noise function once, spawn a seeded swarm, and on every frame step each agent along the field and draw the tiny segment it traveled — never clearing in poster mode:
// One-time setup
const noise = makeNoise(seed); // from AUTHORING.md
const rnd = mulberry32(seed);
const agents = Array.from({ length: N },
() => ({ x: rnd() * W, y: rnd() * H, life: (rnd() * MAXLIFE) | 0 }));
function stepAndDraw(ag) {
const a = fbm(noise, ag.x * scale * 0.004, ag.y * scale * 0.004) * TAU; // a) angle
const px = ag.x, py = ag.y;
ag.x += Math.cos(a) * step; // b) step…
ag.y += Math.sin(a) * step;
ctx.strokeStyle = cosPalette((a / TAU + 0.5) % 1, A, B, C, D); // d) color
ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(ag.x, ag.y); ctx.stroke(); // …and draw
// respawn if it wandered off the canvas or got old (see pitfalls)
if (--ag.life < 0 || ag.x < 0 || ag.x > W || ag.y < 0 || ag.y > H) {
ag.x = rnd() * W; ag.y = rnd() * H; ag.life = (rnd() * MAXLIFE) | 0;
}
}
Note the * 0.004 tucked into the angle line: pixel coordinates are large
numbers (0–1200), and noise wants small inputs (it varies over a unit of ~1). That tiny
factor converts "pixels" into "noise space" so the field has a sane wavelength; the
scale slider then rides on top of it. Get this constant wrong and your field
is either one flat direction or pure static — see the pitfalls.
Common pitfalls
- Over-clearing erases the painting. The big one. A
clearRectat the top of the loop wipes every accumulated segment each frame, so the ink never builds and your "broken" flow field is just a thin shimmer of lines. Persistence is the look — in poster mode, don't clear at all. If you want motion, fade with a tiny-alphafillRectinstead. - Field scale too large → chaos; too small → straight lines. Push the scale slider to the max and the field becomes turbulent static — agents jitter and no ribbons form. Drop it near zero and every agent points almost the same way, giving boring parallel streaks. The sweet spot (≈1–2.5 here) is where you get sweeping curves with structure. There's no "correct" value; it's a creative dial.
- Agents leaving the canvas. An agent that follows the field off the
edge keeps marching into the void, contributing nothing. Detect when
x/yleaves[0,W]×[0,H]and respawn it at a fresh seeded random spot. Same for a max lifespan, so paths stay short and the texture stays even instead of a few agents hogging the frame. - Opacity too high blows out to solid. A
globalAlphanear 1 paints opaque on the first pass and you get flat slabs of color, not silky density. Keep per-segment alpha low (≈0.05) so ink accumulates gradually — the magic is in the stacking. - Frame-rate-dependent drift. If you ever scale
stepby anything other than a fixed amount, multiply it by a clampeddtso the piece paints at the same rate on a 60Hz and a 144Hz screen. Here we keep step fixed and cap how many segments accumulate, which sidesteps it. - DPR blur. Size the canvas's backing store to
devicePixelRatio(capped at 2) or your crisp hairlines turn into soft mush on a retina display — and your saved PNG comes out half-resolution.
Exercises
- Make the field breathe. Add a slowly advancing time term as a
third noise dimension by offsetting the inputs:
fbm(noise, x*scale + t*0.0008, y*scale), and switch to the tiny-alpha fade instead of hard persistence. The whole field will writhe like smoke, and the ribbons will reorganize forever. Suddenly it's a living wallpaper, not a still. - Two overlaid fields. Build a second
makeNoise(seed + 99)and a second palette, run half your agents on each, and let them paint into the same canvas. The two currents interfere and the palettes blend where they cross — instant depth and a far richer image than one field gives. - Vary line width by speed. The field angle changes faster in some
regions than others. Track each agent's turn rate (the change in angle between frames)
and set
ctx.lineWidthfrom it — thin where the flow is calm, thick where it churns. The drawing gains a hand-inked, calligraphic weight.
What's next
Episode 05 — Trigonometry & Cycles. We snuck
cos and sin into this episode to turn an angle into a step — but
that little pair is the engine behind all smooth motion: orbits, waves,
pulsing, easing, springs, the lot. Next we slow down and really learn to think in
circles, so that any time you want something to move smoothly, you'll reach for sine
without thinking. Once you have flow fields and trig in hand, you can drive a
field with a wave — or move the whole thing to the GPU in the
shaders series, where a million agents is cheap.