Home 02: Start drawing
Content
Cancel

02: Start drawing

Now it’s time to start coding.

If you like, you can watch the video first, where I walk you through everything step-by-step, or you can read the introduction.

First we need to create a new file in Visual Studio Code, give it a name, for example my-first-drawing.js, remember that the ending .js is important, and open p5canvas. As soon as you open a JavaScript file in Visual Studio Code, a small icon will appear that says p5canvas in the bottom-left corner of your editor. Just press it to open the extension.

Now let us start and draw some things onto the canvas. To achieve that, we need to know some instructions or commands to draw. First, we want to draw a rectangle. p5.js has a command that we can use for that:

1
rect(x, y, width, height, [radius]);

As you can see, it starts with the name of the command rect (short for rectangle) followed by an opening bracket ( and some placeholders, like x, y, width and height. The placeholder radius is in squared brackets because it is optional. That means, we don’t have to fill in a value for it. After the so-called parameters, it ends with a closing bracket ) and a semicolon ;. As you remember, every statement in JavaScript ends with a semicolon.

The first part is the name of the command, the brackets executing this command and the parameters inside the brackets are used to give more information to the command.

You will see this syntax during the following chapters, the cheatsheets and in the official reference that you can find here.

Let’s start by filling in some values for the placeholder parameters and write it into our JavaScript file. The placeholder x refers to the x-position, the placeholder y to the y-position, and the placeholder width and height to the width and height of the rectangle that we want to draw. The p5canvas will update automatically once your code is written and has no errors.

1
rect(60, 80, 106, 42);

This command tells the computer to draw a rectangle at the position x = 60 pixels and y = 80 pixels, with a width of 106 pixels and a height of 42 pixels. Remember that the origin, the 0,0 point on the canvas, is always in the top-left corner.

A white rectangle on a canvas with rulers on the side Our first rectangle

You should play around and add some more rectangles. Try to draw them on different positions, with different sizes, overlap them and change the order of your commands.

If you are finished with that, you can move on and add some color in the next part.

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