p5.js
a cheat sheet
for beginners!
program structure
//runs once when program starts
function setup(){
createCanvas(800,600); //width,height in pixels
}
//run continuously after setup
function draw(){
//rendering loop
}
system variables
windowWidth / windowHeight
//width / height of window
width / height
//width / height of canvas
mouseX / mouseY
//current horizontal / vertical mouse position
pmouseX / pmouseY
//previous horizontal / vertical mouse position
non-visual feedback
print();
//report data to the output console
//double slash to comment code (program skips it)
color
fill(120); //gray: 0-255
fill(100,125,255); //r, g, b: 0-255
fill(255, 0, 0, 50); //r, g, b, alpha
fill('red'); //color string
fill('#ccc'); //3-digit hex
fill('#222222'); //6-digit hex fill
color(0, 0, 255); //p5.Color object
math
+ - / * //basic math operators
random(low,high); //ranged random number
random(["red", "yellow", "blue"]);
//pick one thing from an array of things
map(value, in1, in2, out1, out2);
//map a value from input range to output range
2d primitives
line(x1, y1, x2, y2);
circle(x, y, diameter);
rect(x, y, width, height);
arc(x, y, width, height, start, stop);
beginShape();
vertex(x1, y1);
vertex(x2, y2);
vertex(x3, y3);
//add more vertex
endShape(CLOSE);
text("string", x, y, boxwidth, boxheight);
-
grid system
-
line()
-
circle()
-
rect()
-
arc()
-
vertex()
attributes
background(color);
//set the background color
//These affect shapes drawn AFTER them
fill(color);
//set the fill color for next shapes
noFill();
//disables fill for next shapes
stroke(color);
//set the stroke color for next shapes
strokeWeight(weight);
//set the stroke’s width in pixels
noStroke();
//disables stroke
rectMode(MODE);
//Coords are for CENTER or CORNER?
angleMode(MODE);
//DEGREES or RADIANS (default)
textSize(pixels);
if/then logic
if(test){
//statements
} else {
//alternative statements.
}
=== //equal to
!= //not equal
> //greater than
< //less than
>= //greater than or equal
<= //less than or equal
loops
for (let i = 0; i < 5; i++){
//statements
}
for (let oneThing of myArrayOfThings){
//statements
}