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);
}
}
}
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.
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);
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);
stroke()
function.This example uses nested for loops to create a radial gradient.
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!