RGB Gradient in Processing

Viewed 991

I'm trying to figure out a way to generate a gradient that should look like this: RGB Gradient

However, I don't know how to combine multiple colors (red, blue, and green) at once. Here is how my code looks like at the moment:

color red;
color blue;
color green;

void setup() {
  size(255, 255);
  
  red = color(255,0,0);
  blue = color(0,0,255);
  green = color(0,255,0);
  
  for(int x = 0; x < width; x++) {
    float n = map(x, 0, width, 0, 1);
    color newc = lerpColor(blue, red, n);
    stroke(newc);
    line(0, x, height, x);
  }
}
void draw() {
} 

As you can see, the color green is currently not being used as I can't find a way to interpolate these colors while retaining the red and blue gradient. I'm a beginner in Processing so I would appreciate some help regarding this. How should I write my code?

1 Answers

I would do this using a nested loop and do the three values separately, like this:

void setup() {
  size(255, 255);
  
  for (int x = 0; x < width; x++) {
    for(int y = 0; y < height; y++) {
      stroke(y, x, 255 - y);
      point(x, y);
    }
  }
}

Here is how you want the colors to change:

  • Red: 0 at the top (where y = 0) and 255 at the bottom (where y = 255)
  • Green: 0 at the left (where x = 0) and 255 at the right (where x = 255)
  • Blue: 255 at the top (where y = 0) and 0 at the bottom (where y = 255)

If you wanted to have a different size canvas, you could use map():

stroke(map(y, 0, height, 0, 255), map(x, 0, width, 0, 255), map(y, 0, height, 255, 0));

or lerp():

float xprop = float(x) / width;
float yprop = float(y) / height;
stroke(lerp(0, 255, yprop), lerp(0, 255, xprop), lerp(255, 0, yprop));
Related