Simple Procedural Gradients

A classic way to generate a smooth series of colours.

Colour from a single number

This technique for generating colours lets you turn a single value into a colour that will smoothly change as the input value varies. This is very useful for colouring things like heat maps that you might normally just shade in greyscale. So long as the repeat set of values are integers the colour will also cycle smoothly if you loop from 1 back to 0, which makes it convenient for many more uses.

The creation of the colour is a fairly simple operation, and on modern hardware can be safely done in realtime. The code isn't as immediately clear in Javascript, so I've included a short pseudocode version too.

// in a language with good vector support
function generateColour(t) {
   return constant + multi * cos(2 * pi * repeat + phase);
// in plain javascript
var PI2 = 6.28319;
function generateColour(t) {
   if (t < 0.0 || t >= 1.0) t -= Math.floor(t);
   return {
      r: clamp(
         constant.r + multi.r * Math.cos(
            PI2 * (repeat.r * t + phase.r)
      g: clamp(
         constant.g + multi.g * Math.cos(
            PI2 * (repeat.g * t + phase.g)
      b: clamp(
         constant.b + multi.b * Math.cos(
            PI2 * (repeat.b * t + phase.b)

Creating a Palette

I think it's easiest to learn how the various parameters influence the palette by just experimenting for yourself. To understand how it works I recomment hitting the simplyRed preset button to turn down all the other channels. Fiddle with the first of each of the sliders and you'll soon see what effect they have on the cosine pattern. To actually create a palette I usually just hit random until something nice shows up and tweak it a little. I used a palette from this in my pixel smoke demo if you'd like to see it in action in something simple.

By the way, my apologises if the slider controls look a little odd in your browser. It turns out everyone likes to render them substantially differently. I think I've got the CSS in a state where they're at least usable in all major browsers. The complete Javascript source for this demo is available, although most the code is to link up the sliders and so on. It's just the generateColour() function given above that's important.