Moon Ha

performer-composer / researcher

p5.js Cheatsheet: Quick Reference Guide

This page is a work in progress, serving as a personal reference for p5.js tips that I keep forgetting. Please note that my posts are not meant to be comprehensive or flawless—consider them a starting point and feel free to add your own insights!

Variables
let i;
let j = [];
Predefined Functions
1. Initialization and Setup
preload(): Used to load external files (images, sounds) before the sketch starts, ensuring they are ready when the sketch begins.
setup(): Runs once at the start of the sketch, used for initializing settings such as canvas size, background color, and other one-time setups.

2. Drawing and Animation
draw(): Continuously executes the code inside it, allowing for animations and updates to the canvas. It runs in a loop after setup().

3. User Interaction
mousePressed(): Called when the mouse is pressed. Useful for handling mouse click events.
mouseReleased(): Triggered when the mouse button is released.
mouseClicked(): Activated when the mouse is clicked (pressed and released).
mouseMoved(): Runs whenever the mouse moves across the canvas.
mouseDragged(): Executes when the mouse is dragged while pressed.
touchStarted(): Triggered when a touch begins on a touch-enabled device.
touchMoved(): Runs when a touch is moved on a touch-enabled device.
touchEnded(): Called when a touch ends on a touch-enabled device.
Keyboard Interaction
keyPressed(): Called whenever a key is pressed.
keyReleased(): Triggered when a key is released.
keyTyped(): Activated when a key is typed (pressed and released).

4. Window and Resizing
windowResized(): Called when the browser window is resized, allowing for adjustments to the canvas or other properties.

5. Other Event Handlers
deviceMoved(): Triggered when the device (such as a phone or tablet) is moved, typically used with accelerometer data.
deviceTurned(): Called when the device orientation changes, often used with gyroscope data.
deviceShaken(): Runs when the device is shaken.

6. Miscellaneous
drawBackground(): Typically used to set up the initial background (if not directly managed in setup() or draw()).
keyIsDown(): Checks if a specific key is currently pressed.
mouseIsPressed: A boolean that is true if the mouse is currently pressed.
Audio Visualization and Playback Example
let song;          // Declare a variable to hold the audio fil
let amplitude;     // Declare a variable for amplitude analysis
let playButton;    // Declare a variable for the play button

function preload() {
  // Load the audio file
  song = loadSound('sounds/milesdavis.mp3');
}

function setup() {
  createCanvas(400, 200);
  background(200);

  // Create a button to control audio playback
  playButton = createButton('Play/Pause');
  playButton.mousePressed(toggleAudio);
  
  // Position the button on the canvas
  playButton.position(10, 10);
  
  // Initialize the amplitude analyzer
  amplitude = new p5.Amplitude();
}

function draw() {
  background(200);

  // Get the current volume level
  let level = amplitude.getLevel();
  
  // Map the volume to circle size
  let size = map(level, 0, 1, 0, 200);
  
  // Draw a circle with size proportional to volume
  ellipse(width / 2, height / 2, size, size);
}

// Function to toggle audio playback
function toggleAudio() {
  if (song.isPlaying()) {
    song.pause();  // Pause the song if it’s already playing
  } else {
    song.play();   // Play the song if it’s not playing
  }
}

// Ensure the audio context is resumed on touch devices, if your audio file isn't loading correctly, try this:

function touchStarted() {
  getAudioContext().resume();
  return false; // Prevent default behavior
}
Basic 2D Shapes
Ellipse: ellipse(x, y, width, height)

Rect (Rectangle): rect(x, y, width, height)

Line: line(x1, y1, x2, y2)

Triangle: triangle(x1, y1, x2, y2, x3, y3)

Quad (Quadrilateral): quad(x1, y1, x2, y2, x3, y3, x4, y4) // Draws a four-sided polygon with four vertices.

Arc: arc(x, y, width, height, start, stop, [mode]) // Draws a segment of an ellipse.

Point: point(x, y)

Bezier Curve: bezier(x1, y1, x2, y2, x3, y3, x4, y4) // Draws a cubic Bézier curve.

Vertex: Used within a beginShape() and endShape() block to create custom shapes.

beginShape();
vertex(x1, y1);
vertex(x2, y2);
vertex(x3, y3);
endShape(CLOSE);
Curve: curve(x1, y1, x2, y2, x3, y3, x4, y4) // Draws a curve through four points.

Curve Vertex: curveVertex(x, y) // Used within a beginShape() and endShape() block to create smooth curves.
3D Shapes
p5.js offers some 3D capabilities through the WEBGL renderer.

Box (Cuboid): box(width, height, depth)

Sphere: sphere(radius) 

Cone: cone(radius, height)

Cylinder: cylinder(radius, height)

Torus: torus(r1, r2) // Draws a 3D torus (doughnut shape).
Example for 3D Rendering
function setup() {
  createCanvas(600, 400, WEBGL);
}

function draw() {
  background(200);
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  box(100);
}
Dynamic Function Execution Queue
let functionQueue = [];

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(255, 255, 255);
  for (let func of functionQueue){
    try {
      func();
    } catch (e){
      background(255, 0, 0);
    }
  }
}

function func0() {
  text("function #0", width/2, height/2);
}

function func1() {
  text("function #1", width/2, height/2 + 40);
}

functionQueue[0] = func0;
functionQueue.push(func1);

Posted in

Reply

Your email address will not be published. Required fields are marked *