Home 02: Add some color
Content
Cancel

02: Add some color

Next, we want to add some color to our drawing. Let us change the color of the rectangle to be red. For that, we can use the following p5.js command:

1
fill(r, g, b);

As you can see, it follows the same convention as before. fill is the name of the command, and r, g, and b are the parameters of it.

About color in computer programs

Let’s talk about colors in computer programs again, you might remember it from the last course.

The three parameters, r, g and b stand for red, green, and blue, and they are used to mix the color you want to have. These parameters can have a value between 0 and 255. Per default, the color-mode is always RGB.

You can use the values from color pickers integrated into your favorite graphic program, like Figma, Sketch, or Photoshop, or you can use an online color picker like this here.

In addition to using the RGB-values, you can use a hex-code for a color or you can use a different color-mode like HSB. To find out more about the different ways to use the fill command, check out the reference here.

Try it yourself

Let’s add some values to the command and write it into our JavaScript file. We will write it on top of the rect command because the order of the code is important.

1
2
fill(255, 0, 0);
rect(60, 80, 42, 106);

A red rectangle Our rectangle has a color now

The fill command in the first line tells the computer that everything that is drawn from now on has a red filling because we set the red value to 255 and the other values to 0. In the next line we tell the computer to draw a rectangle, and because everything is filled red from now on, it is a red rectangle.

If we want to change the fill-color for the following shapes, we have to add another fill command.

Pay attention to the order of the commands. If we would move the fill command under the rect command, the rectangle would not be red, because our program executes the statement from top to bottom.

1
2
rect(60, 80, 42, 106);
fill(255, 0, 0);

A white rectangle As you can see, the order is important

Here are some more commands for drawing shapes and lines.

1
ellipse(x, y, width, [height]);
1
line(x1, y1, x2, y2);

You can look up more commands for drawing shapes in the reference here.

1
stroke(r, g, b);

And you can look up more commands to control colors, strokes, and fills here.

Your turn

Play around with different colors and shapes and try out different orders and how that have an impact on what is drawn on the canvas.

This post is licensed under CC BY 4.0 by the author.
Contents