Saturday, April 29, 2023

weaving the rainbow, understanding color modes in p5

TLDR summary/spoiler: colorMode(HSB) is an easy way to generate rainbow colors.

ChatGPT, even the vaunted 4 version, was surprisingly bad at helping me make a heart shape in P5, so I found this nice little example by "Mithru". But beyond the decent little heart bezier:

function heart(x, y, size) {
  beginShape();
  vertex(x, y);
  bezierVertex(x - size / 2, y - size / 2, x - size, y + size / 3, x, y + size);
  bezierVertex(x + size, y + size / 3, x + size / 2, y - size / 2, x, y);
  endShape(CLOSE);
}

I was trying to figure out how this code made a rainbow array of hearts:

function draw() {
  background(0);
  for (x = 0; x < width; x += s) {
    for (y = 0; y < height; y += s) {
      fill(310*x/width, 127, 255);
      heart(x+s/2, y+s/2, s/2);

    }
  }
}

The first fill value is essentially mapped from 0 to 310 going across the screen,  and then 127 and 255 are locked in.

So how the heck would changing red (presumably with those out out range values) make a rainbow? Well, it doesn't, I missed the colorMode call:

  colorMode(HSB);

Aha - the first value is the "Hue" (0-360 like a circle), second is saturation, third is brightness. I made a simple toy to see it even more in action, mapping mouseY and mouseX to the other values..




Definitely handy to know when you're thinking in rainbow-y ways! And having one value that roughly maps to "color"- it seems simpler than thinking about R and G and B playing together.

No comments:

Post a Comment