examples / processing / for-loops / radial-gradient

Radial Gradient

example processing for-loop
void setup() {
  size(256, 256);
  noSmooth();
}

void draw() {
  for(int y = 0; y < height; y++){
    for(int x = 0; x < width; x++){
      float distanceFromCenter = dist(x, y, width/2, height/2);
      stroke(distanceFromCenter);
      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 distance from the center, and draws the pixel in that color. This creates a radial color gradient.

gradient

All of the magic happens on these two lines:

float distanceFromCenter = dist(x, y, width/2, height/2);
stroke(distanceFromCenter);

This code uses the dist() function to get the distance between each pixel and the center of the window. It then passes that distance into the stroke() function, which sets a grayscale color. The center of the window will have a distance of 0, which causes it to be drawn in black. The edges of the window have a higher distance, so they’re drawn in lighter shades. Pixels between the center and the edges are drawn in a color that scales with the distance, which creates a radial gradient.

Try playing with the parameters passed into the stroke() function. Subtracting the distance from 255 will invert the colors:

stroke(255-distanceFromCenter);

gradient

And don’t be afraid to experiment with colors by adding parameters and multiplying the distance by a scalar:

stroke(255-2*distanceFromCenter, 0, 100);

gradient

gradient gradient gradient

Tweak Ideas