Getting a gradient RGB line using lerp

So I found some code that used lerp to create a gradient between black and white and I modified it to create a gradient between red and blue, but I’d like it to span the whole RGB spectrum:

void gradient_line( color s, color e, float x, float y, float xx, float yy ) {
  for ( int i = 0; i < 100; i ++ ) {
    stroke( lerpColor( s, e, i/100.0) );
    line( ((100-i)*x + i*xx)/100.0, ((100-i)*y + i*yy)/100.0, 
      ((100-i-1)*x + (i+1)*xx)/100.0, ((100-i-1)*y + (i+1)*yy)/100.0 );
  }
}

float px, py;

void setup() {
  size(600, 600);
  px = 300;
  py = 300;
}

void draw() {
  background(128);
  gradient_line( color(255, 0, 0), color(0, 0, 255), mouseX, mouseY, px, py );
}

Is there a simple way to do this?

Hi,

For this, the best is to use the HSB color mode. With some minor modification to your code, you get the desired effect:

void gradient_line( float s, float e, float x, float y, float xx, float yy ) {
  for ( int i = 0; i < 100; i ++ ) {
    stroke( lerp( s, e, i/100.0), 100, 100 );
    line( ((100-i)*x + i*xx)/100.0, ((100-i)*y + i*yy)/100.0, 
      ((100-i-1)*x + (i+1)*xx)/100.0, ((100-i-1)*y + (i+1)*yy)/100.0 );
  }
}

float px, py;

void setup() {
  size(600, 600);
  colorMode(HSB, 360, 100, 100);
  px = 300;
  py = 300;
}

void draw() {
  background(128);
  gradient_line(0, 360, mouseX, mouseY, px, py );
}
2 Likes