p5.js Architecture and Execution Model

How setup, draw, and event handlers interact in a p5.js sketch

flowchart TD Start(("Program Start")):::startNode Setup["setup()
Runs once"]:::setupNode Draw["draw()
Runs continuously
60 FPS (default)"]:::drawNode Canvas["Canvas Display
Updates every frame"]:::canvasNode Events["Event Handlers
mousePressed()
keyPressed()
slider events"]:::eventNode Start --> Setup Setup --> Draw Draw --> Canvas Draw --> Draw Events -.->|State changes| Draw Draw -.->|Read state| Events classDef startNode fill:#667eea,stroke:#333,stroke-width:3px,color:#fff,font-size:16px classDef setupNode fill:#4facfe,stroke:#333,stroke-width:2px,color:#fff,font-size:16px classDef drawNode fill:#f77f00,stroke:#333,stroke-width:2px,color:#fff,font-size:16px classDef canvasNode fill:#95a5a6,stroke:#333,stroke-width:2px,color:#fff,font-size:16px classDef eventNode fill:#9b59b6,stroke:#333,stroke-width:2px,color:#fff,font-size:16px linkStyle default stroke:#999,stroke-width:2px,font-size:14px linkStyle 3 stroke:#e74c3c,stroke-width:3px,stroke-dasharray:5 linkStyle 4 stroke:#3498db,stroke-width:2px,stroke-dasharray:5 linkStyle 5 stroke:#3498db,stroke-width:2px,stroke-dasharray:5

Execution Model

p5.js sketches follow a specific execution pattern with two main functions (setup and draw) plus optional event handlers that respond to user input.

Core Functions

setup() - Initialization

Runs: Once at program start

Purpose: Initialize canvas, set initial variable values, load assets

Example:

function setup() {
  createCanvas(800, 600);
  background(220);
  frameRate(60);
}

draw() - Main Loop

Runs: Continuously at 60 FPS by default

Purpose: Render graphics, update animations, check game state

Example:

function draw() {
  background(220);
  circle(mouseX, mouseY, 50);
}

Event Handlers

Triggered by user input: Mouse clicks, key presses, slider changes

Can modify state: Update global variables that draw() uses

Examples:

Global Variables

Variables 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
}