Shapes
The Canvas
Before we can start drawing shapes, we need to write some code that might seem cryptic if you are new to programming. I will explain the code in detail later. For now just write/copy the code to the shapes.js file.
function setup() {
createCanvas(400, 400);
background(50);
}
When you open the index.html file now, there should be a gray square on the upper left corner of your browser. As you can see there are two parts: the setup and draw. These are JavaScript functions. Whatever you put inside setup will run once, and the code inside draw will run in a loop. The s.createCanvas(400, 400)
creates a 400*400 pixel canvas that we can draw in.
Functions
We will use functions from the P5js library to draw shapes. Functions are "self contained" modules of code that perform a specific task. The P5js library have a set of functions for drawing 2-d shapes. When we call a function from the library, we start by writing s.
and then the name of the P5js function. We have already used a P5js function when we wrote the s.createCanvas(400, 400)
line above. As you can see, the s.createCanvas()
takes two parameters. We have given the function 400 for both. The first value is the number of pixels for the X-axis on our canvas, and the second for the Y-axis.
The image above is a small part of our canvas. In our case the numbers continue to 400 in both the x and y direction. Each square is a pixel. To draw something, we have to specify where we want to draw on this grid. A simple function for drawing something in P5js is the dot()
function. We will use this function in the next section.
If you are having problems gettings things to run, don't worry. You can download the code here: https://github.com/arashsa/learn-p5js. On github you have the option of downloading a project as a zip file (the "Download Zip" button). Read the instructions on how to use the code.