Examples / Processing Examples / For Loops / 2D Gradient

example processing for-loop pretty
``````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.

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!

## 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.