Creative Coding From Zero · Episode 02
Randomness & Noise
Randomness & Noise is Episode 02 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 .
Turn on a dead TV channel and you get static: every pixel a fresh, independent coin
flip, no pixel caring what its neighbors are doing. That's Math.random().
Now picture wind moving through grass, ripples crossing a pond, the rolling silhouette
of a mountain range. Those are also random — no two blades, ripples, or peaks
are identical — but they're smooth: each value flows gently into the
next. That second kind of randomness is called noise, and it is the
single most important tool in generative art.
This episode makes two words click that you'll use in every later episode: seed and noise. A seed turns chaotic, unrepeatable randomness into randomness you can reproduce forever — type the same number, get the same piece, byte for byte. Noise turns jagged static into organic, flowing fields you can sculpt with two sliders. The demo below walks both ideas up from raw static to a field of particles drifting on invisible wind. It animates the moment it loads — no input required.
The stage dropdown picks which idea you're looking at. The
noise scale and octaves sliders reshape the noise stages
(4–6). The regenerate button picks a fresh seed and restarts — watch
how Stage 1 changes every time, but Stage 2 with the same seed is
identical. That difference is the whole point.
What you're looking at
Six stages, one system, each a visibly different state of "randomness." The first
three are about the seed — where randomness comes from and how we tame it. The
last three are about noise — how we make randomness smooth and then put it to
work. Every stage runs on the same two helpers (mulberry32 and a value-noise
field) that you will paste into every future episode, so it's worth getting them in your
fingers now.
Stage 1 — Math.random() scatter
The baseline. We scatter a few thousand dots using the browser's built-in
Math.random(). It looks exactly like TV static: uniform, featureless,
structureless. Each dot is an independent draw with no relationship to any other. Now hit
regenerate. The whole field reshuffles into a different random
arrangement — and here's the problem: you can never get this exact arrangement
back. If this scatter happened to look amazing, it's gone. There's no number you
can write down to reproduce it. For generative art, that's a dealbreaker.
Stage 2 — Seeded RNG (the big idea)
Same scatter, but now every dot comes from a seeded random number
generator: mulberry32. A seeded RNG is a deterministic machine — you give it
one starting number (the seed, shown in the badge), and it produces a fixed
stream of "random-looking" values. Same seed in, same stream out, every single
time, on every machine, forever. Hit regenerate and the seed changes to a new
number and you get a new (but still reproducible) scatter. The static looks just
as random as Stage 1 — your eye can't tell the difference — but this one has a name. Write
down the seed and you can summon this exact image a hundred years from now.
Stage 3 — The random walk
Our first structure built from seeded randomness. Start a dot in the center. Every step, ask the seeded RNG for a small random nudge in x and y, and move. Repeat a few thousand times, drawing the path. The result is a "drunk walk" — a meandering, self-tangling thread. Because it's seeded, the same seed always draws the same wandering path. This is the first hint that random numbers aren't just for noise-on-a-screen; chained together, they generate form.
Stage 4 — 1D noise vs. random
Now the reveal. We draw two lines across the screen. The top line is
jagged: each x asks the RNG for an independent random height, so it
spikes up and down violently — that's raw randomness as a curve. The bottom line is
smooth: each x reads a noise function, noise(t),
and the heights flow gently into one another like a rolling hill. Same underlying
randomness, but noise correlates neighbors — nearby inputs give nearby outputs.
That smoothness is the entire difference between "static" and "wind."
Stage 5 — The 2D noise field
Push noise into two dimensions. For every pixel block we evaluate fbm(x, y)
— fractal (layered) noise — and paint it as a grayscale value: dark in the valleys, bright
on the ridges. The result looks like clouds, marble, or a satellite view of terrain. Drag
the noise scale slider: small scale zooms in (big soft blobs), large
scale zooms out (busy, almost static-like). Drag octaves: one octave is
smooth and blobby; more octaves layer in finer and finer detail, turning smooth hills into
craggy mountains. This grayscale field is the raw material of procedural terrain, textures,
and the flow fields coming in later episodes.
Stage 6 — Noise-driven motion
Finally, we put the field to work. Thousands of particles drift across the screen, and at each one's location we read the noise field to decide which way it should move — the noise value becomes an angle. Particles flow along invisible contours, swirling and braiding like leaves on a breeze or iron filings around a magnet. This is a flow field, and it is one of the most beloved effects in all of generative art. We'll dedicate a whole episode to it later — but you can already see the magic: structure-from-noise, motion-from-a-field.
How the code works
Everything in this episode rests on two helpers. They're short, they're the same in every episode of this series, and once you understand them you understand 80% of how generative art gets its texture. Let's build them up.
(a) mulberry32 — and why seeding matters
A seeded RNG is just a function that mangles its internal state into a new
pseudo-random number each time you call it — and crucially, it starts from a number
you choose. mulberry32 is a tiny, fast, well-distributed generator
that's perfect for art (it is not cryptographic, and that's fine):
// Seeded RNG: mulberry32. Same seed → same stream → same artwork.
function mulberry32(seed) {
let a = seed >>> 0; // force a 32-bit unsigned int
return function () {
a |= 0; a = (a + 0x6D2B79F5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296; // → [0, 1)
};
}
// The contract that makes generative art reproducible:
const rndA = mulberry32(12345);
const rndB = mulberry32(12345);
rndA() === rndB(); // true — and true for every call after, forever
That last line is the whole reason we never call bare Math.random() in the
art path. Math.random() has no seed you can set; its stream is different on
every page load and unrecoverable. Route every "random" decision in your piece — positions,
colors, sizes, walk steps — through a single mulberry32(seed) instance and the
entire artwork becomes a pure function of that one seed. Save the seed, save the piece.
Share the seed, share the piece.
(b) makeNoise and fbm — smoothing the chaos
Raw RNG gives independent values: neighbors are unrelated, so it looks jagged. Value
noise fixes that by laying random values on an integer grid and smoothly
interpolating between them with a soft fade curve. The result is continuous —
noise(1.0) and noise(1.001) are nearly equal. fbm
("fractal Brownian motion") then sums several noise layers at doubling frequency and
halving amplitude, adding detail without losing the overall flow:
// 2D value noise + fbm: smooth, organic, deterministic. Seeded too.
function makeNoise(seed) {
const r = mulberry32(seed);
const p = new Uint8Array(512), perm = new Uint8Array(256);
for (let i = 0; i < 256; i++) perm[i] = i;
// shuffle the gradient table with the seeded RNG → reproducible noise
for (let i = 255; i > 0; i--) { const j = (r() * (i + 1)) | 0; [perm[i], perm[j]] = [perm[j], perm[i]]; }
for (let i = 0; i < 512; i++) p[i] = perm[i & 255];
const fade = t => t * t * t * (t * (t * 6 - 15) + 10); // smootherstep
const lerp = (a, b, t) => a + t * (b - a);
const grad = (h, x, y) => ((h & 1) ? -x : x) + ((h & 2) ? -y : y);
return function noise2D(x, y) { // output ~[-1, 1]
const X = Math.floor(x) & 255, Y = Math.floor(y) & 255;
x -= Math.floor(x); y -= Math.floor(y);
const u = fade(x), v = fade(y);
const aa = p[p[X] + Y], ab = p[p[X] + Y + 1];
const ba = p[p[X + 1] + Y], bb = p[p[X + 1] + Y + 1];
return lerp(lerp(grad(aa, x, y), grad(ba, x - 1, y), u),
lerp(grad(ab, x, y - 1), grad(bb, x - 1, y - 1), u), v);
};
}
function fbm(noise, x, y, oct = 4) { // layered noise → richer texture
let s = 0, amp = 0.5, f = 1;
for (let i = 0; i < oct; i++) { s += amp * noise(x * f, y * f); f *= 2; amp *= 0.5; }
return s;
}
Notice makeNoise takes a seed too — it shuffles its gradient table
with mulberry32, so the same seed produces the same noise field. Reproducibility
runs all the way down.
(c) Rendering the grayscale field
Stage 5 draws the field with one ImageData buffer. We loop over a coarse
grid of cells (not every pixel — that's the speed trick), evaluate fbm, and
here's the must-not-skip step: noise comes out roughly in [-1, 1], but
color channels want [0, 1], so we remap before converting to
a 0–255 byte:
// Paint fbm(x,y) as grayscale into an ImageData buffer.
const img = ctx.createImageData(W, H);
const data = img.data;
const cell = 4; // resolution: bigger = faster, blockier
for (let y = 0; y < H; y += cell) {
for (let x = 0; x < W; x += cell) {
const n = fbm(noise, x / W * scale, y / H * scale, octaves);
const g = (n * 0.5 + 0.5) * 255; // remap [-1,1] → [0,1] → [0,255]
// splat this value across the whole cell block
for (let j = 0; j < cell; j++) for (let i = 0; i < cell; i++) {
const idx = ((y + j) * W + (x + i)) * 4;
data[idx] = data[idx + 1] = data[idx + 2] = g;
data[idx + 3] = 255;
}
}
}
ctx.putImageData(img, 0, 0);
That single line n * 0.5 + 0.5 is the most-forgotten line in all of
procedural texturing. Skip it and half your field clamps to black, because every negative
noise value becomes 0.
(d) Noise → position and angle (motion)
Stage 6 turns the field into movement. Each particle reads the noise at its current spot, scales that value up into a full rotation, and steps in that direction. We draw on a faintly-faded canvas instead of a hard clear, so the paths leave gentle trails:
// Each frame: nudge every particle along the noise field.
for (const pt of particles) {
// sample fbm at the particle's location (scaled into noise space)
const n = fbm(noise, pt.x / W * scale, pt.y / H * scale, octaves);
const angle = n * Math.PI * 2; // noise value → direction
pt.x += Math.cos(angle) * speed;
pt.y += Math.sin(angle) * speed;
if (pt.x < 0 || pt.x > W || pt.y < 0 || pt.y > H) respawn(pt); // recycle off-screen
}
That's the seed of every flow field, smoke sim, and "particles following an invisible
current" piece you've ever admired. The field is the same fbm you painted in
Stage 5; we just read it for direction instead of brightness.
Common pitfalls
Math.random()sneaks into the art path. The instant a single un-seeded random call decides anything visual — a position, a color, a jitter — your piece stops being reproducible, because that one value changes every load. Funnel everything through onemulberry32(seed)instance. (This is exactly the difference between Stage 1 and Stage 2.)- Wrong noise scale. Too large a scale and adjacent pixels land in totally different grid cells — the noise degenerates back into static-looking hash. Too small and you're sampling a tiny patch of one cell, so the whole field is nearly flat and featureless. The sweet spot (a handful of cells across the screen) is what makes it look organic. Sweep the slider in Stage 5 to feel both failure modes.
- Octaves aren't free. Each octave doubles the noise lookups for that sample. Seven octaves is seven times the cost of one. For a per-pixel field that adds up fast — render at a coarse cell size, or cache the field instead of recomputing it every frame, when you can.
- Forgetting to remap the range.
noisereturns roughly[-1, 1]. Color, alpha, and size all want[0, 1](or[0, 255]). Alwaysn * 0.5 + 0.5before you treat a noise value as a brightness — otherwise every negative sample clamps to black and you lose half your dynamic range. - Clearing vs. trailing. Stage 6 paints a translucent rectangle each
frame instead of fully clearing, so motion leaves trails. A hard
clearRectwould erase the flow lines instantly. Decide on purpose which one you want — it's the #1 "why does my flow field look wrong."
Exercises
- Animate the field. In Stage 5, feed time into the noise:
fbm(noise, x*scale, y*scale + t*0.001, octaves). The whole grayscale field starts flowing like drifting clouds — a 2D field sampled through a moving slice of a 3D-ish space. (This is also a free upgrade for Stage 6's motion.) - Threshold into islands. After computing the field value, snap it:
g = (n > 0 ? 255 : 20). The smooth field collapses into a black-and-white map of "islands" and "ocean." Sweep the threshold and watch coastlines grow and shrink — that's procedural map generation in one line. - Tint by height with a palette. Instead of gray, map the remapped value through a color ramp: deep blue → sand → green → snow-white as the value climbs. You now have a fantasy terrain map. (Episode 07 builds the cosine-palette helper that makes this gorgeous.)
What's next
Episode 03 — Particle Systems: the pattern behind every spark, explosion, fountain, and snowstorm. We give thousands of little dots a position, a velocity, a lifespan, and a force or two, then recycle them in a pool so the frame rate never buckles. Seeded randomness gives each particle its individual character; today's noise field, plugged in as a force, will later turn that particle system into living smoke. Everything compounds from here.