P5.js Reference Guide
Canvas
The area where p5.js drawings are displayed. Created using createCanvas()
.
A good example is a canvas that is 400 wide and 300 high.
We can use two global variables to declare these dimensions.
1 2 3 4 5 6 7 8 |
|
setup()
Called once at the start of the program to define initial environment properties.
1 2 3 4 5 6 |
|
draw()
Continuously executes the lines of code inside its block until stopped.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
stroke()
Sets the color used for lines and borders around shapes.
1 2 3 4 |
|
rect()
- Draws a rectangle.
1 2 3
function draw() { rect(30, 20, 55, 55); }
ellipse()
- Draws an ellipse (oval).
1 2 3
function draw() { ellipse(50, 50, 80, 80); }
line()
- Draws a line.
1 2 3
function draw() { line(30, 20, 85, 75); }
loadImage()
- Loads an image from a path.
1 2 3 4
let img; function preload() { img = loadImage('image.png'); }
image()
- Draws an image to the canvas.
1 2 3
function draw() { image(img, 0, 0); }
createGraphics()
- Creates a new graphics object.
1 2 3 4 5
let pg; function setup() { createCanvas(100, 100); pg = createGraphics(50, 50); }
translate()
- Remaps the (0,0) position on the canvas.
1 2 3 4
function draw() { translate(width / 2, height / 2); rect(0, 0, 30, 30); }
rotate()
- Rotates the entire canvas.
1 2 3 4
function draw() { rotate(PI / 4); rect(50, 50, 100, 50); }
push()
Saves the current drawing style settings and transformations.
1 2 3 4 5 6 7 |
|
pop()
Restores the drawing style settings and transformations previously saved.
1 |
|
frameRate()
Specifies the number of frames to be displayed every second.
1 2 3 |
|
noLoop()
Stops the draw loop. This can be used when a drawing is finished.
1 2 3 4 |
|
loop()
Restarts the draw loop after it has been stopped.
1 2 3 |
|
keyPressed()
Called whenever a key is pressed.
1 2 3 4 5 |
|
mousePressed()
Called whenever a mouse button is pressed.
1 2 3 |
|