Physics and Code Tutorial Live!
1: Coding Basics
1. Draw a Circle
Takeaway
- To draw something on screen, you first need a canvas of a chosen size. The default canvas colour is white.
- Simple shapes can be drawn, their size and location determined by their parameters.
- All location parameters are relative to the top-left corner of the canvas (in other words, the origin (0,0) is at the top-left corner of the canvas).
- Details for all functions can be found on the p5.js reference page, including:
2. setup() vs draw()
Takeaway
- Again: everything in
setup() happens once at the beginning, and everything in draw() happens over and over again (i.e. loops), 60 times every second.
- Functions are executed in order, from top to bottom.
- Reference: setup(), draw()
3. translate()
Takeaway
- The location of the origin can be changed with
translate(x, y).
4. Variables
Takeaway
- The use of variables makes your code easier to read and maintain.
- Variables are user-created and should be descriptive, using camelCase where necessary (e.g.
squareSize and squareSpacing).
- As their name suggests, their values can be changed at any time (to be demonstrated in Physics and Code Tutorial 2).
5. if ()
Goal: "If the cursor is on the right side of the canvas, draw a square on the left side".
Takeaway
- if statements are used to run certain blocks of code only if some condition is met. Otherwise, the code block is ignored.
- Reference: if statement
p5.js Cheat Sheet
| Reference |
Example |
Example Description |
| createCanvas(x,y) |
createCanvas(400, 250) |
Creates a canvas that’s 400 pixels wide and 250 pixels tall. |
| background(color) |
background('green') |
Colours the entire canvas green. (n.b. Colors can be defined a number of different ways.) |
| translate(x, y) |
translate(100, 200) |
Moves the origin to 100 pixels from the left of the canvas and 200 pixels from the top of the canvas. |
| circle(x, y, diameter) |
circle(10,20,30) |
Draws a circle with a 30 pixel diameter 10 pixels to the right of the origin and 20 pixels below the origin. more shapes |
| let |
let animalType = "fox"; |
Creates a variable called animalType (and assigns a value of "fox" to it). |
| if statement |
if (t > 10) {
background('green');
}
|
If the variable t is greater than 10, the canvas will be painted green. |