void setup() {
size(256, 256);
noSmooth();
}
void draw() {
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
float distanceFromTopLeft = dist(x, y, 0, 0);
float distanceFromTopRight = dist(x, y, width, 0);
float distanceFromBottomLeft = dist(x, y, 0, height);
stroke(distanceFromTopLeft, distanceFromTopRight, distanceFromBottomLeft);
point(x, y);
}
}
}
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
This code uses nested for
loops to loop over every pixel in the window. For each pixel, it creates a color based on that pixel’s distance from the corners, and then draws the pixel in that color. This creates a corner gradient.
All of the magic happens on these lines:
float distanceFromTopLeft = dist(x, y, 0, 0);
float distanceFromTopRight = dist(x, y, width, 0);
float distanceFromBottomLeft = dist(x, y, 0, height);
stroke(distanceFromTopLeft, distanceFromTopRight, distanceFromBottomLeft);
This code uses the dist()
function to get the distance between each pixel and the top-left, top-right, and bottom-left corners. It then passes those distances into the stroke()
function, which sets its red, green, and blue components.
Try playing with the parameters passed into the stroke()
function to come up with different colors, or move the points around to create different types of gradients.
stroke()
function.This example uses nested for loops to create a corner 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!