Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 50 ยท Color

Gradients, Palettes and Dithering

Interpolate colors for gradients and color maps, understand indexed palettes, and compare threshold, ordered (Bayer) and Floyd-Steinberg dithering live.

Colors rarely stay still. A sky fades from blue to orange, a heat map runs from cold to hot, a game fades a texture to black. All of these need color interpolation: computing the colors in between two or more known ones. The reverse problem is just as important. Sometimes you must squeeze a picture into fewer colors, for a GIF, a retro display, an e-ink screen or a tiny file. Done naively you get ugly bands; done well, with dithering, a handful of colors can imitate thousands.

This lesson covers both directions: building gradients and color maps with linear interpolation (and the traps of the color space), then reducing colors with palettes and three dithering methods that you can compare side by side.

Linear interpolation of colors

The basic tool is lerp, linear interpolation. Given two values a and b and a fraction t from 0 to 1:

TEXT
lerp(a, b, t) = a + (b - a) * t = (1 - t) * a + t * b

At t = 0 you get a, at t = 1 you get b, and t = 0.5 is exactly halfway. For a color you apply lerp to each channel separately. The gradient from red (255, 0, 0) to blue (0, 0, 255) at t = 0.25 is (191, 0, 64).

In the RGB cube, this is a straight line from one corner to another, which is why the same formula also blends textures and antialiases edges. The same idea fills triangles with smoothly varying colors, as you saw in triangle rasterization, where the weights t come from barycentric coordinates.

The space matters

Where you interpolate changes the look:

  • In encoded sRGB (the default of most software). Easy, but the middle of a gradient between two saturated colors can look dull or too dark. Red to green passes through a murky brown-olive.
  • In linear light. Decode, lerp, encode (see the gamma section). This is physically correct for mixing light and brightens the middle compared with the first option.
  • In HSV or HSL. Move around the color wheel instead of through the cube, so red to green passes through bright orange and yellow. Take the shorter way around the hue circle, and beware that grey endpoints have no meaningful hue.
  • In a perceptual space (Oklab, Lab). Gives the most even-looking steps for color scales and smooth gradients; CSS lets you ask for it with linear-gradient(in oklab, ...).

There is no universally best choice; choose it per task, and make sure that the same one is used in both the code that draws and the code that analyses.

Color maps: from numbers to colors

A color map (or lookup table, LUT) turns a single number in [0, 1] into a color. Scientific plots, heat maps, terrain elevations and medical images all use them. A color map is built from a few stops, colors at positions along 0 to 1, with linear interpolation between neighbouring stops:

JavaScript
function colorMap(stops, t) {
  t = Math.min(1, Math.max(0, t));
  const scaled = t * (stops.length - 1);
  const i = Math.min(stops.length - 2, Math.floor(scaled));
  const f = scaled - i;
  return stops[i].map((c, k) => c + (stops[i + 1][k] - c) * f);
}

Good color maps for data follow rules: lightness changes steadily (so that the order of values is visible even in greyscale), there are no sudden bright bands that fake edges in the data (the old "rainbow" or "jet" map is infamous for this), and the colors stay distinguishable for people with color-vision deficiencies. Viridis is a well-known map designed this way. Other kinds are diverging maps (two hues meeting at a neutral middle, for data with a meaningful center like temperature anomalies) and qualitative palettes (distinct colors for categories, with no order).

The demo draws three gradients between red and green using different spaces, followed by three color maps built from a handful of stops.

Gradients in different spaces, and color maps

Compare rows 1 and 2: the linear-light version has a brighter yellowish middle, while the plain sRGB blend dips into a dark olive. Row 3 stays saturated the whole way. In row 4 the heat map rises steadily in lightness, so it still reads correctly in greyscale.

Indexed color and palettes

Storing three bytes for every pixel is wasteful when a picture only uses a few colors. Indexed color stores a small table, the palette, of up to 256 colors, and each pixel holds just a one-byte index into it. GIF and 8-bit PNG work this way, as did early VGA hardware.

flowchart LR
  I["Index buffer<br/>(1 byte per pixel)"] -->|"index 2"| P["Palette<br/>0: black<br/>1: white<br/>2: orange<br/>..."]
  P --> C["Display color<br/>(R, G, B)"]

Each pixel stores a palette index; the palette turns it into a real color.

Indexed color also enables palette animation: changing one palette entry recolors every pixel that uses it, with no pixel written. Old games used it for water, fire and fades.

Converting a full-color image to a palette needs two steps: choose a good palette (color quantization, with methods such as median cut, which repeatedly splits the set of colors along its widest channel), and then map each pixel to its nearest palette color, usually by smallest squared distance in RGB. The mapping step is sketched here with a 4-color palette.

JS Nearest palette color

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The mid-grey (128, 128, 128) is far from every palette color, and its nearest match is just a guess. A whole region of such greys would turn into one flat patch. That is banding, and dithering is the cure.

Dithering: faking colors with patterns

When you must show a tone that the palette lacks, you can mix the available colors in space. A grey that is 50% white is shown as a checkerboard of black and white pixels; your eye, which blurs fine detail, sees grey. This is dithering. We will look at three methods, all for reducing a grey image to a few levels.

  1. Threshold (no dithering). Round each pixel to the nearest level. Fast, but smooth areas become flat bands and contours.

  2. Ordered dithering. Compare each pixel with a fixed threshold matrix, tiled over the image. The classic is the 4 x 4 Bayer matrix:

    TEXT
     0   8   2  10
    12   4  14   6
     3  11   1   9
    15   7  13   5
    

    Each cell holds a number from 0 to 15, spread so that low and high thresholds are far apart. For a black-and-white result, a pixel is white if its value is larger than (cell + 0.5) / 16. Dark areas get few white dots, bright areas get many, and the pattern is regular and cross-hatched. It needs no memory and is perfectly parallel, which is why it is also used on GPUs.

  3. Error diffusion (Floyd-Steinberg). Round the pixel, compute the quantization error (the difference between the wanted value and the shown one), and spread that error to the pixels not yet processed: 7/16 to the right, 3/16 below-left, 5/16 below, 1/16 below-right. A pixel that was rounded down passes its lost brightness to its neighbours, so over a region the average is exact.

flowchart TD
  X["current pixel (rounded to nearest level)"] -->|"7/16"| R["right neighbour"]
  X -->|"3/16"| BL["below-left"]
  X -->|"5/16"| B["below"]
  X -->|"1/16"| BR["below-right"]

Floyd-Steinberg pushes the rounding error onto four unprocessed neighbours.

Error diffusion gives the most natural, film-like result, but it has to process pixels in order (it is sequential), and it may show worm-like patterns in flat areas. Ordered dithering is regular and stable between animation frames, which is why it is popular for games and retro looks.

The demo builds a test picture (a ramp on top, a glowing disc below) and shows four versions side by side: the original, plain rounding, Bayer, and Floyd-Steinberg. Change the number of grey levels between 2 and 4.

Threshold, Bayer and Floyd-Steinberg

With two levels, the rounding-only version has just a single sharp edge in the ramp and a flat disc; the dithered ones keep a smooth-looking gradient and a recognisable glow. The disc shows the difference in character: Bayer gives a regular crosshatch, Floyd-Steinberg gives irregular grain. At four levels the contrast between the three methods becomes subtler.

One caveat: for simplicity the demo works directly on the displayed values. A fully correct implementation would dither in linear light and then encode, otherwise the average brightness of the pattern is slightly off, as in the gamma discussion of the previous lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the color halfway between (200, 100, 0) and (0, 100, 200) when you lerp each channel?

    Each channel is the average: (200+0)/2 = 100, (100+100)/2 = 100, (0+200)/2 = 100.
  2. 2. In indexed color, what does each pixel store?

    The palette holds the real colors, and each pixel stores only a small index into it, which saves memory.
  3. 3. How does Floyd-Steinberg dithering produce a good average tone?

    The part of the brightness lost by rounding is added to the neighbours (7/16, 3/16, 5/16, 1/16), so the region's average stays correct.
  4. 4. Which is an advantage of ordered (Bayer) dithering over error diffusion?

    Each output pixel depends only on its own value and the matrix cell, which suits GPUs and animation, at the cost of a visible regular pattern.
  5. 5. Why is the old rainbow ('jet') color map considered a poor choice for data?

    A good map increases lightness steadily. The rainbow has bright bands that look like boundaries in smooth data and loses its order in greyscale.

Summary

  • Color interpolation is lerp(a, b, t) = a + (b - a) * t applied to each channel; the space you interpolate in (sRGB, linear, HSV, perceptual) changes the look.
  • A color map turns a number in [0, 1] into a color through stops; choose maps with steadily changing lightness for data.
  • Indexed color stores a palette plus one index per pixel; quantization chooses the palette, and nearest-color search maps pixels to it.
  • Dithering trades spatial detail for tonal range: ordered dithering uses a fixed threshold matrix (Bayer), and Floyd-Steinberg spreads the rounding error to neighbours.

Next, we move from 2D into space: 3D Points and Transformation Matrices.