Basics
## Basic Template
function setup() {
createCanvas(400, 300); // your drawing area
background(220); // canvas color
}
function draw() {
// this runs 60 times per second
}
## Background
background(0); // 0, black; 255 white;
background(r,g,b);
## line & shapes
ellipse(x, y, width, height);
line(x1, y1, x2, y2);
triangle(x1, y1, x2, y2, x3, y3);
rectMode(CENTER); //x1,y1, at the center of the rectangular
## colors & outlines
fill(r, g, b);
fill(0, 0, 255, a); // a controls transparency; 0 =transparent; 255=oppaque
noFill();
stroke(r, g, b);
noStroke();
strokeWeight(4);
## variables
let x = 0;
x = x + 1; (or: x += 1) (or, x ++)
### common shorthands
x+=1 //to increase the value by 1 each loop.
x-=1 //to decrease the value by 1 each loop.
x*=2 // to double the value each loop
x/=2 //to halve the value each loop
## Common parameters
width
heigheit
mouseX
mouseY
## randomness
random(min,max)
## for Loop syntax
function draw() {
for (let i = 0; i < 10; i++) {
// repeat this code 10 times
}
function draw() {
for (let x = 20; x < width; x += 40) {
ellipse(x, 100, 30);
}
}
//Conditional: IF Else
if (x > 200) {
fill(255, 100, 100); // light red
} else {
fill(100, 150, 255); // light blue
}
function setup(){
textSize(48);
textAlign(CENTER, CENTER);}
text ("sink",x,y)
Advanced
In p5.js, **all event functions must be defined in the global scope**:
function setup() { }
function draw() { }
function mousePressed() { }
function mouseReleased() { }
function mouseMoved() { }
function keyPressed() { }
function keyReleased() { }
function keyTyped() { }
If they are inside another function, **they will not run**.
frameRate(10); // <-- slow down to 10 frames per second
console.log(frameRate()); // prints the current FPS
arc(x, y, w, h, startAngle, endAngle);
/*
0 radians → pointing to the right
PI radians → pointing to the left
TWO_PI → full circle (all the way around)
*/
--> the if syntax
function draw() {
if (mouseIsPressed) {
circle(mouseX, mouseY, 20);
}
}
console.log("SPACEBAR!");
function keyPressed() {
if (key === "r") {
background(255, 0, 0); // R = turn background red
}
if (key === "c") {
background(255); // C = clear canvas
}
if (key === " ") {
console.log("SPACEBAR!");
}
}
Remainder
a % b: This calculates the remainder when a is divided by b.
Example: 10 % 3 = 1 (because 3 goes into 10 three times with 1 left over).
--> texts
function setup() {
createCanvas(400, 200);
textSize(48);
textAlign(CENTER, CENTER);
}
function draw() {
background(220);
text("HELLO", width / 2, height / 2);
}
Other
print(x <= 200);
--> will print true if x <= 200, otherwise will print false;
--> a function with input that returns a calculated value...
function celsiusToFahrenheit(c) {
return c * 9 / 5 + 32;
}