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

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

map(value, in1, in2, out1, out2);
//map a value from input range to output range

2d primitives

line(x1, y1, x2, y2);

ellipse(x, y, width, height);

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()

  • ellipse()

  • rect()

  • arc()

  • vertex()

attributes

background(color);
//set the background color

fill(color);
//set the fill color

noFill();
//disables fill

stroke(color);
//set the stroke color

strokeWeight(weight);
//set the stroke’s width in pixels

noStroke();
//disables stroke

ellipseMode(MODE);
rectMode(MODE);
//CENTER,CORNER

textSize(pixels);

if/then logic

if(test){
  //statements
}

===  //equal to 
!=  //not equal
>   //greater than
<   //less than
>=  //greater than or equal
<=  //less than or equal