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);
}
}
}
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.
x,y
of 0,0
, so the color will be 0,0,0
, which makes it black.x,y,
of 0,255
, so the color is 0,0,255
, which makes it blue.x,y
of 255,0
, so the color is 0,255,0
, which makes it green.x,y
of 255,255
, so the color is 0,255,255
, which makes it blue-green (technically this color is called cyan).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!
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!stroke()
function.This example uses nested for loops to create a 2D 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!