Creative Coding From Zero · Episode 07
Color & Palettes
Color & Palettes is Episode 07 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 .
Here is the uncomfortable truth about generative art: the math is the easy part. You can write a flawless flow field, a perfect particle system, noise so smooth it sings — and it will still look like garbage if the colors are wrong. Nine times out of ten, the line between a frame-worthy piece and AI slop isn't the algorithm. It's the color. Muddy, random RGB is the single loudest tell that a human never looked at the output.
This episode is a palette engine. We'll start from the worst possible color choice —
pure random r,g,b — and climb, stage by stage, to a tuned cosine palette
(the famous Inigo Quilez trick) that makes any generative piece sing. Along the
way: why HSL beats raw RGB, color harmony rules borrowed from painters, canvas gradients,
and a dithering pass that kills the ugly banding on smooth ramps. The demo below is the
same composition rendered six different ways. Watch it go from trash to art.
Six stages, one canvas, all driven by the same seed so the shape never
changes — only the color does. That's the whole point: hold the composition fixed and
let color do the heavy lifting. The preset dropdown swaps cosine-palette coefficients;
the d and c sliders reshape the ramp by hand; the dither toggle
is most visible on stages 4 and 6. Hit ↻ new seed to reroll the
underlying field, and save PNG to keep a frame.
What you're looking at
Every stage renders to the same off-DPI canvas with the same seeded random stream
(the mulberry32 generator from Episode 02, reused here so the art is
reproducible). Nothing animates wildly — color work is best judged on a calm surface —
but the cosine ramp drifts its phase and a few stages breathe so the piece is alive on
first paint. Here's the journey, one <h2> per stage.
Stage 1 — RGB is mud
Start with the anti-pattern. Fill a grid of swatches with three independent random
numbers each — r, g, b, all from
[0,255]. This is what almost every first generative sketch does, and it is
almost always wrong. The result is a sea of muddy, desaturated sludge: olive,
brown, gray-purple, the color of a puddle in a parking lot.
Why? Because random RGB samples a cube uniformly, and the middle of the RGB cube — where all three channels are mid-range — is exactly where mud lives. Vivid, pleasing colors cling to the cube's edges and corners, a tiny fraction of the volume. Uniform sampling almost never lands there. Worse, neighboring swatches share no relationship at all, so there's no harmony, no theme, nothing for the eye to rest on. This is the look people mean when they say generative art looks "AI-generated."
Stage 2 — HSL harmony
The fix is to stop thinking in RGB and start thinking in HSL: hue, saturation, lightness. Instead of three free axes of mud, you get one perceptual knob per quality. Constrain the hue to a narrow band (the hue-range slider), pin saturation high so colors stay vivid, and let lightness vary to give range. Suddenly the same grid of swatches is instantly, almost unfairly, harmonious — a controlled spread of one color family instead of random sludge.
Drag the hue-range slider and watch the whole grid rotate around the color wheel while staying coherent. A 60° range reads as "a palette"; a 360° range reads as "confetti." This is the first real lesson of color in code: constraint is the source of harmony. You almost never want the full gamut.
Stage 3 — The cosine palette
HSL is great for picking colors, but it's awkward for building a smooth ramp
— a continuous gradient of color you can index with a single number t ∈ [0,1].
For that, the gold-standard trick in generative art is Inigo Quilez's
cosine palette. One formula, four RGB coefficients, infinite tasteful
gradients:
color(t) = a + b · cos( 2π · (c · t + d) )
Read it channel by channel. a is the midpoint (the average brightness),
b is the amplitude (how far the color swings), c is the
frequency (how many color cycles across the ramp), and d is the phase (where
each channel starts). Because each of R, G, B gets its own cosine with a slightly
different phase, the three channels rise and fall out of step — and that
out-of-step-ness is exactly what produces rich, vivid, never-muddy gradients.
Drag the phase d and contrast c sliders to reshape the ramp
live, or pick a preset to jump between curated coefficient sets.
Stage 4 — Gradients from the palette
Canvas has its own gradient machinery: createLinearGradient and
createRadialGradient. They take color stops and interpolate between them in
hardware. The trick is to feed them from the palette — sample the cosine ramp at
a handful of t values and use those as the stops. Now your gradient inherits
the palette's harmony instead of being two arbitrary hand-picked colors.
This stage shows a linear gradient panel and a radial glow, both built from the same cosine coefficients as stage 3. Switch presets and both gradients re-stop instantly. This is also where banding first becomes visible — long smooth ramps on an 8-bit display show staircase artifacts — which is the cue for the dither toggle. More on that below.
Stage 5 — Color harmony
Painters don't pick colors at random; they pick relationships. Take a base hue and rotate it around the wheel by a fixed angle to get a scheme:
- Complementary — rotate 180°. Maximum contrast, a base and its opposite. Great for a pop of accent against a dominant field.
- Analogous — rotate ±30°. Neighbors on the wheel. Calm, cohesive, the safest "this just looks designed" choice.
- Triadic — rotate ±120°. Three evenly spaced hues. Vibrant and balanced, like a primary-color poster.
This stage shows all three schemes as labeled swatch rows from the current base hue. Drag the hue-range slider (it doubles as the base-hue knob here) and watch each scheme track in lockstep. These three rotations cover the vast majority of color decisions you'll ever make in generative work.
Stage 6 — Apply to art
Now the payoff. We take a real generative composition — a flowing value-noise field
(the fbm from Episode 06) sliced into contour bands — and recolor it live
with whatever palette is selected. This is where everything converges: the noise gives
form, the cosine palette gives color, and the dither toggle gives a
clean surface. Flip dither off and the smooth bands show ugly horizontal banding;
flip it on and an ordered Bayer pattern breaks the bands into invisible noise. Same
field, same palette — the dither is the difference between "smooth" and "cheap."
Swap presets and the entire field re-tints in one frame. That's the deliverable this episode promised: a palette engine you can bolt onto any piece to make it sing.
How the code works
Four building blocks carry the whole episode. Here they are, lifted straight from the demo, in the order you'd reach for them.
(a) An hsl() helper — and why HSL beats raw RGB
Raw RGB asks you to specify light intensities, which is not how humans think about color. HSL asks you to specify hue, saturation, lightness, which is exactly how we think about it. The browser already speaks HSL, so the "helper" is mostly about discipline: pick a hue, keep saturation high, vary lightness — and never reach for three independent random channels.
// HSL → a CSS color string. h in [0,360), s & l in [0,100].
const hsl = (h, s, l, a = 1) =>
`hsla(${((h % 360) + 360) % 360}, ${s}%, ${l}%, ${a})`;
// MUD (don't): three free channels → the middle of the RGB cube.
ctx.fillStyle = `rgb(${rnd()*255|0},${rnd()*255|0},${rnd()*255|0})`;
// HARMONY (do): constrain hue, pin saturation, vary lightness.
const baseHue = 28, range = 60;
ctx.fillStyle = hsl(baseHue + rnd() * range, 75, 45 + rnd() * 25);
The whole jump from stage 1 to stage 2 is exactly those two fillStyle
lines. One samples a cube of mud; the other samples a wedge of one harmonious family.
(b) The cosine palette (the IQ formula)
This is the workhorse — copy it once and reuse it forever. Each argument is an
[r,g,b] triple; t is your position along the ramp. The clamp
keeps channels in range even when the cosines overshoot.
// Cosine palette (Inigo Quilez): t in [0,1] → vivid, harmonious color.
function cosPalette(t, a, b, c, d) { // each arg is [r,g,b]
const f = (i) => Math.round(255 * Math.max(0, Math.min(1,
a[i] + b[i] * Math.cos(6.28318 * (c[i] * t + d[i])))));
return `rgb(${f(0)},${f(1)},${f(2)})`;
}
// A nice default — warm "sunset" ramp:
const A = [.5, .5, .5], B = [.5, .5, .5],
C = [1, 1, 1], D = [0, .1, .2];
for (let i = 0; i < 12; i++) {
ctx.fillStyle = cosPalette(i / 11, A, B, C, D); // 12 swatches across the ramp
ctx.fillRect(i * w, 0, w, h);
}
The four presets in the demo are just four different [a,b,c,d] sets. That's
the magic: a curated palette is twelve numbers. The phase d slider nudges all
three d channels together (a color cycle), and contrast c scales
the frequency (a tighter or looser ramp).
(c) A canvas gradient from palette stops
Don't hand-pick gradient stops — sample them from the palette so the gradient is automatically harmonious. A handful of stops is enough; the browser interpolates the rest.
// Build a linear gradient whose stops come from the cosine ramp.
const g = ctx.createLinearGradient(0, 0, W, 0);
const STOPS = 6;
for (let i = 0; i <= STOPS; i++) {
const t = i / STOPS;
g.addColorStop(t, cosPalette(t, A, B, C, D));
}
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
// Radial works the same — a glow from palette center to edge.
const rg = ctx.createRadialGradient(cx, cy, 0, cx, cy, R);
rg.addColorStop(0, cosPalette(0.15, A, B, C, D));
rg.addColorStop(1, cosPalette(0.9, A, B, C, D));
(d) Ordered (Bayer) dithering to break up banding
An 8-bit display has only 256 levels per channel. A long, smooth gradient asks for more steps than that, so adjacent pixels snap to the same value and you see banding — visible stripes in what should be a silky ramp. The classic, cheap fix is ordered dithering: add a tiny, structured offset from a Bayer matrix before quantizing, so the boundary between two levels is scattered into a fine checker the eye blends into a smooth tone.
// 4×4 Bayer matrix, normalized to roughly [-0.5, 0.5].
const BAYER = [
0, 8, 2,10, 12,4,14,6,
3,11, 1, 9, 15,7,13,5
].map(v => (v / 16) - 0.5);
// When writing a pixel, nudge each channel by the Bayer value (in 0–255 units)
// before it gets quantized to 8-bit. ~1.5 levels of spread kills most banding.
function dither(value, x, y) {
const b = BAYER[(y & 3) * 4 + (x & 3)] * 1.5;
return Math.max(0, Math.min(255, value + b));
}
// data[idx] = dither(r, x, y); etc. — applied per pixel in an ImageData loop.
In the demo, dithering is applied in the per-pixel ImageData loop for
stages 4 and 6, where smooth ramps live. Toggle it off on stage 6 and the contour bands
show hard steps; toggle it on and they melt. It's a handful of integer adds per pixel —
practically free, and the most underrated polish step in the whole pipeline.
Common pitfalls
- Muddy random RGB. The number-one tell of un-art-directed output. Three independent random channels sample the center of the color cube, which is exactly where mud lives. Fix: never do it — route every color through HSL or a cosine palette and constrain the range.
- Over-saturation. The opposite failure: pinning saturation to 100% everywhere gives a garish, eye-searing neon mess that reads as "amateur" just as loudly as mud. Fix: vary lightness, pull a few colors toward gray, and let the palette breathe. Tasteful means some restraint.
- Banding on smooth gradients. Long ramps stair-step on 8-bit displays. Fix: ordered/Bayer dithering — a tiny structured offset before quantizing (block d above). Almost free, and it's the difference between "smooth" and "cheap."
- Forgetting sRGB / gamma. Canvas color math (and CSS color strings)
operate in sRGB, which is gamma-encoded, not linear light. Averaging two
sRGB colors at the midpoint gives a muddier result than averaging in linear space.
For most 2D work the browser hides this, but the moment you blend in an
ImageDataloop or composite withglobalAlpha, the midtones go murky. Fix: know which space you're in; for critical blends, decode to linear, mix, re-encode. - Too many hues. A piece with twelve unrelated hues has no identity. Fix: limit the palette. Two or three hues plus their tints and shades will out-design a rainbow every time.
Exercises
- Extract a palette from a noise seed. Feed a seed into
mulberry32, draw four random numbers, and map them onto the cosine coefficients (e.g. perturbdbyrnd()per channel and pickcfrom a small set). Now every seed yields a different but always tasteful palette — the engine the pros use to generate hundreds of coherent variations. - Animate
dfor a color cycle. In your render loop, addtime * 0.05to the palette'sdvalues each frame. The whole piece cycles smoothly through related hues without ever going muddy — because the cosine keeps the channels in their tasteful relationship. (Thephase dslider in the demo is the manual version of this.) - Build a "palette of the day." Seed
mulberry32with today's date as a number (e.g.20260605) and generate a palette from it. Every day the site greets the visitor with a new, deterministic, never-muddy color scheme — and it's identical for everyone who loads it that day.
What's next
Episode 08 — The Generative Poster (season finale). We compose everything from the series — seeded randomness, noise, particles, gradients, and this episode's palette engine — into a single one-click art generator: hit a button, get a frame-worthy poster, save the PNG. Color is the last ingredient that was missing; now we plate the whole dish. You'll cross-link this naturally to the shaders series (move the palette to a fragment shader and tint a million pixels in parallel) and the three.js series (generative color in 3D).