p5.js Session 12: Colour, HSB and RGB

How RGB and HSB colour work, why HSB suits generative art, and how opacity blends colours together.

In Session 11 we built our own shapes with vertex() and splineVertex(). This session leaves shape aside and looks at colour itself.

RGB, a recap

Every colour we’ve used so far has been RGB: red, green, and blue, each from 0 to 255. Mixing the three gives you any colour on screen, but picking a specific hue this way takes some guessing, there’s no single number that means “orange.”

HSB: hue, saturation, brightness

HSB describes colour differently: hue is the colour itself, one number around a wheel from 0 to 360. Saturation is how vivid it is, 0 is grey, 100 is fully saturated. Brightness is how light or dark it is. colorMode(HSB) switches p5.js over to reading colours this way.

Let’s put twelve circles in a row and give each one a hue a little further around the wheel than the last.

function setup() {
  createCanvas(650, 200);
  colorMode(HSB, 360, 100, 100);
  noLoop();
  noStroke();
}
function draw() {
  background(0, 0, 0);
  for (let i = 0; i < 12; i++) {
    let hueValue = i * 30;
    fill(hueValue, 80, 90);
    circle(50 + i * 50, 100, 40);
  }
}

A row of 12 circles shifting through the full colour spectrum using HSB

This is why HSB suits generative art so well: cycling through colour is just counting, rotating a single number around the wheel, instead of juggling three RGB values at once.

Opacity: the alpha channel

Both RGB and HSB accept a fourth number in fill(): alpha, or opacity. 0 is fully invisible, the maximum (255 in RGB, 100 in HSB) is fully opaque.

Two overlapping circles, neither of them solid, show what that actually does.

function setup() {
  createCanvas(600, 600);
  noLoop();
  noStroke();
}
function draw() {
  background(0);
  fill(200, 50, 50, 150);
  circle(240, 300, 300);
  fill(50, 100, 200, 150);
  circle(360, 300, 300);
}

Two overlapping circles, red and blue, both partially transparent, blending into a third colour where they meet

Alpha works exactly the same way in colorMode(HSB), just add it as the fourth value there too.

The scripts in this session were written for p5.js 2.3.2, the version the web editor runs by default.


Next session, we take colour further: building a reusable palette, stored in an array, instead of picking values one at a time.