How setup, draw, and event handlers interact in a p5.js sketch
p5.js sketches follow a specific execution pattern with two main functions (setup and draw) plus optional event handlers that respond to user input.
Runs: Once at program start
Purpose: Initialize canvas, set initial variable values, load assets
Example:
function setup() {
createCanvas(800, 600);
background(220);
frameRate(60);
}
Runs: Continuously at 60 FPS by default
Purpose: Render graphics, update animations, check game state
Example:
function draw() {
background(220);
circle(mouseX, mouseY, 50);
}
Triggered by user input: Mouse clicks, key presses, slider changes
Can modify state: Update global variables that draw() uses
Examples:
mousePressed() - Called when mouse button is clickedkeyPressed() - Called when keyboard key is pressedmouseDragged() - Called when mouse is moved while button is downVariables declared outside functions are accessible throughout the sketch. Event handlers can modify these variables, and draw() can read them to update the display.
let x = 0; // Global variable
function setup() {
createCanvas(400, 400);
}
function draw() {
circle(x, 200, 50);
x += 1; // Update position
}
function mousePressed() {
x = 0; // Reset on click
}