Submodule 16.2: Basics of p5.js
Submodule 16.2: Basics of p5.js
- setup() and draw() functions
- createCanvas
- Primitives Shapes
setup() and draw() functions
The first thing that you will need in order to start coding in p5.js, is to understand the setup() and draw() functions.
The setup() function should be placed at the beginning of our code. We can only have one setup() function and it is the place where we initialize our environment. That setup() function runs only once in the beginning of the program.
Inside that function, we initialize the dimensions of our canvas. We will see more about that later but essentially our canvas is the place where our code will take place.
Also, in the setup() we can choose to define the background color of our canvas.
Example of a code with an empty canvas of green background:
function setup() {
// create canvas
createCanvas(800,500);
// set background color
background('#31bc33');
}
The draw() function should always be placed after the setup() function and we can only have one such function in our code. It is called automatically up to 60 times per second and it works similar to loops. It continuously executes everything that is inside its block.
All our main code is placed inside this block.
- See more about setup() and draw() functions
- See more about the background() function