Creative Coding From Zero · Episode 11
Reaction-Diffusion
Reaction-Diffusion is Episode 11 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 .
Two numbers per pixel and one little equation. That's the whole machine. Call the
numbers A and B — two imaginary chemicals soaking through a
grid. Let them spread out a bit, let them react where they touch, and then just step
time forward, over and over. What grows out the other side is uncanny: coral, leopard
spots, fingerprints, brain folds, cells that bulge and split in two. Nobody draws those
shapes. They emerge, the way they do in a developing animal, from a rule so
small it fits in a tweet.
This is the Gray-Scott model, the most famous member of a family
Alan Turing dreamed up in 1952 to explain how a featureless egg decides where to put
stripes. Below is a live one, running entirely on a raw 2D canvas — no GPU, no shaders,
just a couple of Float32Array buffers and the same arithmetic forty times a
second. Drag two sliders and you walk from spots to mazes to dividing blobs. Click and
you inject chemical and watch a pattern bloom out of your cursor. By the end you'll be
able to grow your own.
What you're looking at
Every pixel of that simulation holds two values: how much of
chemical A is there, and how much of chemical B. We start with
A everywhere (a full tank) and a few seeded splats of B. Then
each frame we run the same three-step recipe — diffuse, react, repeat — a few
times over, and recolor the grid. The stage dropdown peels the model open one layer at a
time: first the bare grid, then diffusion alone, then the reaction alone, then both
together, then the parameter presets that pick which life-form grows, and finally the
styled version you can paint into.
The single most important thing to notice: the simulation does not run at the canvas's pixel resolution. It runs on a small grid — about 220×140 cells — and that little image is stretched up to fill the frame. That's the whole performance trick, and we'll come back to why it's non-negotiable. For now, just know that the gorgeous high-res look is a cheap upscale of a tiny, fast simulation.
Stage 1 — The two-chemical grid
Before any physics, just the substrate. Picture a shallow dish. Pour in chemical
A until it's full everywhere — every cell starts at A = 1.
Chemical B starts at zero except for a handful of seeded squares
where we drop B = 1. In the demo this stage renders A as the
dark background and the B splats as bright dots. Nothing moves yet; this is
frame zero, the canvas the rest of the model paints on.
Why two chemicals and not one? Because one substance, left alone, just spreads out
and flattens — boring. The magic needs a predator and prey: B
consumes A to make more of itself, while a steady drip refills
A and a steady drain removes B. That tension — feed one, kill
the other, let them eat each other in between — is what holds a pattern in a permanent,
living almost-balance instead of letting it die flat.
Stage 2 — Diffusion: the Laplacian blurs each chemical
Diffusion is just spreading: a cell gives a little of its chemical to its
neighbors and takes a little from them, so sharp peaks slump and gaps fill in. The
operator that measures "how much does this cell differ from its neighbors' average" is
the Laplacian, written ∇². On a grid it's a tiny weighted
sum over the 3×3 block around each cell. Run diffusion by itself in this
stage and you'll see the seeded B splats soften and bleed outward like ink
in water, then fade — pure blur, no structure. Diffusion alone can never make a pattern.
It's the reaction that fights back.
The classic Gray-Scott kernel weights the four edge neighbors at 0.2,
the four diagonals at 0.05, and the center at -1 (so a flat
region returns zero — nothing to spread). Those weights sum to zero on purpose.
Stage 3 — Reaction: the feed and kill terms
Now turn off the spreading and watch only the chemistry. The reaction is one line:
wherever A and B meet, the reaction
A + 2B → 3B converts A into B at a rate of
A·B² — two units of B grab one of A and turn it
into a third B, autocatalysis, B breeding more B.
Left unchecked that would eat all the A and stop. So two more terms hold the
line: feed drips fresh A back in everywhere (proportional
to how empty the cell is, feed·(1−A)), and kill removes
B at a steady rate. In this stage the pattern doesn't spread spatially — but
each splat pulses as B blooms and burns out. Feed and kill are the two knobs
you'll spend the rest of your life tuning.
Stage 4 — The full Gray-Scott step
Put them together and the system comes alive. Each cell, each tick, does:
diffuse A, diffuse B, apply the reaction, nudge A
and B by the result times a small time step dt. We read from
one buffer and write into a second, then swap them — that's the ping-pong (Stage 4's
star, and the subject of a code block below). Run it and the splats stop being splats:
they grow rims, send out fingers, branch, and lock into a steady texture. This is the
moment reaction-diffusion stops looking like a screensaver and starts looking
biological.
Stage 5 — Feed/kill presets: the parameter map
Here's the wild part. The equation never changes — only two numbers do, and those two numbers select which creature you grow. There's a famous 2D map (feed on one axis, kill on the other) where each region births a different morphology. The preset dropdown jumps you to four landmarks on it:
| Preset | feed | kill | What grows |
|---|---|---|---|
coral | 0.0545 | 0.0620 | Branching coral / fingerprint ridges that keep growing into empty space |
mitosis | 0.0367 | 0.0649 | Cells that swell, pinch, and divide — endless self-replicating blobs |
spots | 0.0300 | 0.0625 | Stable leopard / cheetah spots that hold a hexagonal-ish lattice |
maze | 0.0290 | 0.0570 | Worming labyrinth corridors — stripes that never quite close |
Pick a preset, then drag the sliders a hair off it and watch the morphology morph. The danger zone is everywhere else: stray too far and the pattern either floods to solid or dies to nothing. Living patterns occupy a thin, twisty band in parameter space, which is exactly why we ship working presets instead of leaving you to find them blind.
Stage 6 — Styled: colormap and click-to-inject
The same simulation, dressed up. Instead of plotting raw B as grey, we
map the chemical concentration through a cosine palette — the same
vivid, harmonious colormap from Episode 07 — and add a touch of edge contrast so the
ridges pop. Then we wire up the mouse: click and drag to inject chemical
B straight under your cursor and watch a new colony bloom and
spread into the existing pattern. Hit save PNG to keep whatever you grew. This
is the frame-worthy stage — start here, then go back and understand how it works.
How the code works
Four pieces carry the whole demo. First, the Laplacian — the 3×3 kernel that does the diffusion. We sample the eight neighbors of a cell (wrapping at the edges so the grid is a seamless torus) and combine them with the Gray-Scott weights:
// 3×3 Laplacian on field `f` at cell (x,y), grid W×H, toroidal wrap.
// Weights: edges 0.2, diagonals 0.05, center -1 → sum is 0.
function laplacian(f, x, y) {
const xm = (x - 1 + W) % W, xp = (x + 1) % W; // left / right, wrapped
const ym = (y - 1 + H) % H, yp = (y + 1) % H; // up / down, wrapped
const i = y * W + x;
return (
f[i] * -1.0 +
(f[ym * W + x] + f[yp * W + x] + f[y * W + xm] + f[y * W + xp]) * 0.2 +
(f[ym * W + xm] + f[ym * W + xp] + f[yp * W + xm] + f[yp * W + xp]) * 0.05
);
}
Second, the Gray-Scott update for one cell. This is the entire model
— read A, B, and their Laplacians, then compute the next values
with the two diffusion rates Da, Db and your
feed/kill:
// The whole model, per cell. reaction = A·B² (autocatalysis: B eats A).
const a = A[i], b = B[i];
const reaction = a * b * b;
const a2 = a + (Da * lapA - reaction + feed * (1 - a)) * dt;
const b2 = b + (Db * lapB + reaction - (kill + feed) * b) * dt;
An[i] = a2 < 0 ? 0 : a2 > 1 ? 1 : a2; // clamp to [0,1] for stability
Bn[i] = b2 < 0 ? 0 : b2 > 1 ? 1 : b2;
The diffusion (Da·lapA) spreads each chemical; the reaction moves
A into B; feed·(1−A) tops up A; and
(kill+feed)·B drains B. Four forces, one balance.
Third, the ping-pong buffers. You cannot update a cell in place — its neighbors still need its old value this tick. So we keep two copies of each field, read from the current pair, write into the spare pair, then swap. Doing several such steps per animation frame lets the pattern evolve quickly without redrawing every step:
// Two copies of each field: read `src`, write `dst`, then swap.
let A = new Float32Array(W * H), An = new Float32Array(W * H);
let B = new Float32Array(W * H), Bn = new Float32Array(W * H);
function step() {
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++) {
// ...compute a2,b2 as above, write An[i]/Bn[i]...
}
[A, An] = [An, A]; // swap A buffers
[B, Bn] = [Bn, B]; // swap B buffers
}
// a few steps per frame → fast evolution, one redraw
for (let s = 0; s < 8; s++) step();
Fourth, the render: the small grid → an ImageData →
upscaled onto the canvas. We walk the simulation grid once, map each cell's chemical to
a color, and write four bytes into an ImageData sized to the grid. Then a
single drawImage stretches that tiny bitmap to fill the canvas, with image
smoothing on so the upscale looks like silk, not Lego:
// One ImageData sized to the SIM grid (W×H), not the canvas.
const img = sctx.createImageData(W, H); // sctx = offscreen W×H ctx
function render() {
const px = img.data;
for (let i = 0; i < W * H; i++) {
const v = A[i] - B[i]; // "magnitude": A-rich vs B-rich
const [r, g, b] = colormap(v); // cosine palette → RGB
const j = i * 4;
px[j] = r; px[j + 1] = g; px[j + 2] = b; px[j + 3] = 255;
}
sctx.putImageData(img, 0, 0); // fill the small offscreen
ctx.imageSmoothingEnabled = true;
ctx.drawImage(scratch, 0, 0, cw, ch); // upscale to the big canvas
}
That separation — simulate small, draw big — is the entire reason this runs at 60fps in a plain canvas. Everything else is bookkeeping.
Common pitfalls
- Simulating at full canvas resolution. The number-one killer.
A 1600×1000 canvas is 1.6 million cells; at eight steps a frame that's
thirteen million Laplacians per frame and your fps falls off a cliff. Simulate on a
modest grid (here ~220×140 ≈ 30k cells) into
Float32Arrays and upscale the result withdrawImage. The pattern looks identical and runs a hundred times faster. - Updating in place instead of ping-ponging. If you write the new
value of a cell into the same array you're reading neighbors from, later cells in the
loop see a mix of old and new data and the simulation corrupts into noise or stripes
that drift. Always read from
src, write todst, then swap. - Wandering out of the living band. Patterns only exist for a thin
ribbon of feed/kill values. A little too much kill and
Bdies everywhere (flat); a little too little and it floods (solid). If your screen goes blank or solid, you left the band — snap back to a preset and nudge gently. - Too big a
dt. The update is an explicit Euler step, which is only stable for small time steps. Pushdtpast ~1.0 with these diffusion rates and values explode toNaNand the screen flickers or goes black. Keepdt = 1.0and clampA,Bto[0,1]as a safety net. - Forgetting to seed. A perfectly uniform tank (
A=1,B=0everywhere) is a fixed point — the reaction term is zero, so nothing ever happens, forever. You must inject a perturbation: seed a few splats ofB(or a noisy patch) to break the symmetry and give the pattern something to grow from.
Exercises
- Paint with the mouse. The demo already injects
Bon click — extend it: make the brush radius a slider, and add a modifier (hold a key) to erase by paintingA=1, B=0instead. You've turned a simulation into a coral-drawing tool. - Animate feed/kill over time. Instead of constants, drive
feedandkillwith slow sine waves (or by sampling thefbmnoise from the authoring helpers across the grid). The morphology will crawl continuously between spots, mazes, and coral — a single piece that's never the same twice. - A second species. Add a third field
Cwith its own feed/kill, sharing the sameAtank, and letBandCcompete for it. Two patterns fighting over one substrate produce territory borders and interference you can't get from one species. RenderBandCinto different color channels to see who's winning.
What's next
Episode 12 — Verlet physics: cloth and rope. We leave grids behind for particles connected by constraints. With nothing but positions, a previous position, and a "keep these two points a fixed distance apart" rule applied a few times per frame, you get rope that swings, cloth that drapes and tears, and ragdolls that flop — the same trick that powers a surprising amount of game physics. After a season of fields and pixels, it's a delightfully different way to make things move.
Want to take reaction-diffusion further first? It's a natural fit for the GPU — every cell is independent, so it maps perfectly to a fragment shader and you can simulate at full 4K resolution in real time (that's the shaders series). Or drive the feed/kill from an audio signal to make the coral pulse with music (the audio-reactive series).