Shaders From Zero · Episode 04

Color & Gradients

Color & Gradients is Episode 04 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 04 · Shaders From Zero

A color in a shader is just a vec3 of three numbers. But those three numbers can mean very different things — and which meaning you use changes how easily you can animate, blend, and design with them. This episode is how a shader programmer thinks about color.

By the end you'll have four mental models for color — RGB, HSV, cosine palettes, and the gamma question — and you'll know which one to reach for when. The demo walks you through five gradients, from "the dumbest possible two-color lerp" to "one uniform drives an infinite flowing rainbow." Same plane, same vertex shader, five different ways to fill it with light.

0 fps
ShaderMaterial · GLSL
Two-color mix() across vUv.x. The simplest gradient.

RGB — the default, and its limits

The standard way shaders represent color is three floats: red, green, blue, each in the range [0, 1]. vec3(1.0, 0.0, 0.0) is full red. vec3(0.0, 0.0, 0.0) is black. vec3(1.0, 1.0, 1.0) is white. These map (roughly) to the physical intensity of red, green, and blue light coming out of the three subpixels in your monitor.

The math is easy. The intuition is bad. Take vec3(1.0, 0.5, 0.2). Without thinking, can you tell me what color that is? It's warm orange. Now suppose you want to "rotate that hue 90 degrees toward green." What's the new vec3? You don't know. Nobody knows. RGB is a great storage format and a terrible authoring format.

That's the recurring theme of this episode: the same color has several representations, and the one you pick decides what's easy and what's hard.

Takeaway: RGB is where colors finally live, but it's not where you want to think about them.

HSV — when you want to think about hue

HSV decomposes a color into three more human-shaped numbers:

  • Hue — where on the rainbow you are. An angle from 0 to 360° (or, for shader purposes, 0 to 1). Red is 0, yellow ~0.17, green ~0.33, cyan 0.5, blue ~0.67, magenta ~0.83, back to red at 1.
  • Saturation — how "colorful" vs grey it is. 0 is fully greyscale, 1 is the most vivid version of that hue.
  • Value (sometimes Brightness) — how bright. 0 is black, 1 is the brightest version of the chosen hue.

Animating a rainbow in RGB is a chore — you'd have to know which mixed-channel values produce which intermediate colors. In HSV it's one line:

vec3 col = hsv2rgb(vec3(uTime * 0.1, 0.8, 1.0));
//                       ^ hue marches forward in time
//                                       ^ saturation pinned
//                                            ^ brightness pinned

You need a small conversion function. Here's the classic four-line one by Sam Hocevar — short, branchless, GPU-friendly:

vec3 hsv2rgb(vec3 c) {
  vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
  vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
  return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

Drop it at the top of any fragment shader and call hsv2rgb(vec3(h, s, v)). It looks cryptic because it's been golfed for size, but it's just three offset triangle waves doing the work of three if-branches. Don't try to read it line by line — just trust it and use it.

Stage 3 in the demo uses exactly this: hue across vUv.x, saturation and value pinned. One line, full rainbow.

Power-user note: HSV is great for hue cycling, but it has a known wart — equal steps in hue do not produce equal steps in perceived brightness. A pure yellow (hue ≈ 0.17) reads as much brighter than a pure blue (hue ≈ 0.67) even at the same V. If you need perceptually uniform color, look up OKLab or OKLCh — but for everyday shader work, HSV is plenty.

Takeaway: if you ever find yourself thinking "I want this color but shifted along the rainbow," you want HSV, not RGB.

Inigo Quilez's cosine palette — the secret weapon

HSV is good when you want one specific kind of motion — a hue march. But sometimes you want a palette: a curated sweep of related colors that flow into each other smoothly. Sunrise, electric blue to magenta, neon-on-asphalt. There's a beautiful four-line trick for that.

It's Inigo Quilez's cosine palette:

vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) {
  return a + b * cos(6.2832 * (c * t + d));
}

One float in, one vec3 out. Four vec3 knobs control the shape of the gradient:

  • a — DC offset. The center color the palette oscillates around.
  • b — amplitude. How wide each channel swings around a.
  • c — frequency. How many wave cycles per unit of t, per channel.
  • d — phase. The starting offset of each channel's wave. Different d per channel is where the magic comes from — it desyncs R, G, and B so they sweep through different colors as t moves.

The classic rainbow setup:

vec3 a = vec3(0.5);
vec3 b = vec3(0.5);
vec3 c = vec3(1.0, 1.0, 1.0);
vec3 d = vec3(0.0, 0.33, 0.67);

vec3 col = palette(vUv.x, a, b, c, d);

That's Stage 4. a = 0.5 and b = 0.5 means each channel swings between 0 and 1. c = 1.0 means one full cycle as t goes 0 to 1. d staggers the three channels by 1/3 each, so they peak at different points and you get a clean spectrum.

And the kicker is Stage 5: replace vUv.x with vUv.x + uTime * 0.2, and the entire palette flows across the surface forever. One uniform, infinite motion, no extra state.

Inigo Quilez published this in 2015 at iquilezles.org/articles/palettes. Read it. He gives a half-dozen ready-made (a, b, c, d) sets, with pictures. It's a five-minute read that adds a permanent tool to your kit.

Takeaway: four vec3s, one cosine, infinite palettes. Bookmark IQ's article and steal his coefficients.

Gamma vs linear — the one-paragraph version

Your monitor is not linear. When a pixel value is 0.5, the light coming out is not half as bright as 1.0 — it's closer to 0.22 in linear-light terms. Image formats, web canvases, and screens all operate in sRGB, which is a curve that puts more bits where the eye has more sensitivity (the dark end).

Three.js handles the output conversion for you when you set renderer.outputColorSpace = THREE.SRGBColorSpace. Our template already does that — go look at line 522 of Episode 01 if you don't believe me. With that one line, your shader can write linear-feeling values into gl_FragColor and the renderer applies the right gamma curve on the way out.

The catch: if you do mix(vec3(1,0,0), vec3(0,1,0), 0.5) in shader code, you're mixing the sRGB-encoded numbers 1.0 and 0.0 and getting 0.5 — which then gets de-gamma'd and looks like a muddy olive, not a clean yellow. Technically incorrect, visually what most humans expect, and the overwhelmingly common case in every shader you'll ever read. Don't worry about it yet — there'll be a whole episode on color spaces later in the series.

Takeaway: set outputColorSpace = SRGBColorSpace and forget about it for now. Just know the words exist.

Blending colors with mix

You met mix in Episode 01 — it's the GLSL workhorse for any kind of interpolation. Worth restating in color-specific terms:

vec3 a = vec3(1.0, 0.2, 0.1);   // red
vec3 b = vec3(0.1, 0.4, 1.0);   // blue

vec3 col = mix(a, b, 0.5);     // halfway between

Two-color gradient — drive t from a UV:

vec3 col = mix(warm, cool, vUv.x);   // Stage 1

Three-color gradient — nest two mix calls and use smoothstep to define the regions:

vec3 c1 = vec3(0.95, 0.2,  0.5 );
vec3 c2 = vec3(0.95, 0.85, 0.2 );
vec3 c3 = vec3(0.1,  0.6,  0.95);

float t = vUv.x;
vec3 col = mix(
  mix(c1, c2, smoothstep(0.0, 0.5, t)),
  c3,
  smoothstep(0.5, 1.0, t)
);                                       // Stage 2

The pattern generalizes: for N colors, you nest N−1 mix calls, each one handing off to the next at the right smoothstep boundary. It's verbose, but it does exactly what you'd draw on a napkin.

Animated gradient — drive t with uTime:

float t = sin(uTime + vUv.x * 6.2832) * 0.5 + 0.5;
vec3 col = mix(warm, cool, t);

You wrote this one in Episode 01. The pattern doesn't change as you climb the ladder — what changes is what's inside the colors, and what drives t.

Takeaway: mix is the one function you'll write more than any other. Get fluent.

Common first-day pitfalls

  • Hardcoding RGB triples. You eyeball vec3(0.85, 0.32, 0.41) on your laptop at 80% brightness, ship it, and a friend sees mud on a phone in sunlight. Prefer named palettes — IQ cosine, HSV with consistent saturation/value, or a palette texture. They're easier to tweak and easier to migrate when the design changes.
  • Forgetting outputColorSpace = SRGBColorSpace. Your whole render looks washed-out and dim. One line of renderer setup is the single biggest "why does my Three.js look bad" answer on Stack Overflow.
  • Animating a hue in RGB space. You try to cycle from red to green to blue by lerping the channels and the midpoints come out as muddy browns and greys. Switch to HSV (or an IQ palette) — they're built to keep the chroma high all the way through.
  • Treating mix(red, green, 0.5) as "yellow." It's not. It's a dim olive — because of the gamma issue above. If you want a clean yellow midpoint, either start with a palette designed for it (HSV/IQ) or, eventually, learn to mix in linear-light space.
  • Channel-clipping. If you write gl_FragColor = vec4(col * 1.5, 1.0) and any channel exceeds 1, it silently saturates and you lose hue. The clipped pixel turns pure white at the apex. Watch for it whenever you multiply colors by big numbers.

Exercises

  1. Take Stage 3 (HSV rainbow) and make the rainbow scroll horizontally over time — add uTime * 0.3 to the hue. Notice that because hue is cyclic, it loops seamlessly. (Try the same trick with a three-color mix gradient and watch it not loop seamlessly.)
  2. Modify Stage 4's palette by changing only the d vector. Try d = vec3(0.0, 0.1, 0.2) for a sunset feel, or d = vec3(0.3, 0.2, 0.2) for ocean-to-fire. Spend two minutes just tweaking d; you'll start to feel why phase desync is the heart of the trick.
  3. Build a two-axis gradient: pick four corner colors and use two nested mixes — one across vUv.x, one across vUv.y — so the four corners blend into each other. This is the classic bilinear gradient, and it's how every gradient picker in every design tool actually works.

What's next

Episode 05 — Noise. Until now, every gradient we've made is perfectly regular: a straight line, a clean sine, a smooth palette sweep. Next episode we start adding controlled chaos — the noise functions that turn flat gradients into smoke, water, terrain, and fire. We'll climb the ladder: hash → value noise → Perlin → fractal Brownian motion. That ladder is the foundation under more than half of every organic effect on Shadertoy.