2D Gradient



2D Gradient


void setup() {
  size(256, 256);
  noSmooth();
}

void draw() {
  for(int y = 0; y < height; y++){
    for(int x = 0; x < width; x++){
      stroke(0, x, y);
      point(x, y);
    }
  }
}
Code Editor

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

This code uses a nested for loop to loop over every pixel in the window. For each pixel, it creates a color based on that pixel’s position, and draws the pixel in that color. This creates a 2D color gradient.

gradient

All of the magic happens on this line:

stroke(0, x, y);

This line sets the stroke value to a color based on the x and y variables. Think about some example points, what their x,y values are, and what color that generates when fed into the stroke() function.

  • The upper-left corner will have an x,y of 0,0, so the color will be 0,0,0, which makes it black.
  • The lower-left corner has an x,y, of 0,255, so the color is 0,0,255, which makes it blue.
  • The upper-right corner has an x,y of 255,0, so the color is 0,255,0, which makes it green.
  • The lower-right corner has an x,y of 255,255, so the color is 0,255,255, which makes it blue-green (technically this color is called cyan).
  • Everywhere else is some mixture of blue and green, which is what creates the gradient as the color slowly fades from one color to another.

Try playing with the parameters passed into the stroke() function. Rearrange them to be stroke(x, y, 0) or add in numbers like stroke(x, 100, y) to see what colors you can come up with!

gradient gradient gradient

Tweak Ideas

  • Instead of using the x and y values directly, use the dist() function to base your colors off each point’s distance from the center of the window. This will create a radial gradient!
  • Pass in a random number as one of the parameters to the stroke() function.

For Loops Examples

Comments

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!