Instance Mode in p5.js: The Smart Choice for Web‑Integrated Sketches
When a p5.js sketch lives inside a real website, global mode’s name collisions and automatic canvas placement become a nightmare. This guide explains why instance mode is the practical solution, shows how to instantiate a sketch, and walks through bundler‑friendly examples and verification steps.
30 Sept 2025, 15:31 UTC

Why Global Mode Fails Inside Real Web Pages
When you drop a p5.js sketch onto a blank page, the library automatically looks for setup() and draw() on window. That “global mode” is great for quick demos, but it leaks dozens of names into the global namespace:
width,height,mouseX,mouseY- Drawing functions like
ellipse(),rect() - Event handlers such as
mousePressed()
In a production site you almost always have other scripts, CSS frameworks, or even other p5 sketches. The overlapping names cause hard‑to‑debug collisions: a second mousePressed() will override the first, or width might be overwritten by a layout library. The canvas is also appended to the end of body by default, so you lose control over placement.
Enter Instance Mode
Instance mode keeps every sketch in its own sandbox. Instead of letting p5 create global functions, you explicitly create an object that owns all of its state:
const sketch = (p) => {
p.setup = () => {
p.createCanvas(200, 200);
p.background(200);
};
p.draw = () => {
p.ellipse(p.mouseX, p.mouseY, 30, 30);
};
};
// Create the sketch and attach it to a specific DOM node
const canvasContainer = document.getElementById('sketch1');
new p5(sketch, canvasContainer);
All p5 API calls are now methods on the p instance. Nothing touches window, so no namespace pollution occurs. The constructor’s second argument accepts a DOM node, a selector string, or a reference to an element, giving you fine‑grained control over where the canvas lands.
Bundlers and ES Modules: A Practical Pain Point
Modern workflows use npm and bundlers like Webpack or Vite. In an ES module, top‑level declarations are module‑scoped, meaning global mode’s automatic detection of setup() and draw() never finds them. The sketch simply never starts:
// sketch.js – will not run in global mode
function setup() { createCanvas(400, 400); }
function draw() { background(220); }
Switching to instance mode resolves this:
import p5 from 'p5';
const sketch = (p) => {
p.setup = () => { p.createCanvas(400, 400); };
p.draw = () => { p.background(220); };
};
new p5(sketch, document.getElementById('canvas-root'));
Because the sketch is now a function passed explicitly to the constructor, the bundler keeps it inside the module, and p5 starts as soon as the instance is created.
Multiple Sketches on One Page
Global mode effectively supports only one sketch per page: a second setup() overwrites the first. Instance mode allows you to keep dozens of independent canvases, each with its own state machine and event handlers:
const sketchA = (p) => { /* ... */ };
const sketchB = (p) => { /* ... */ };
new p5(sketchA, document.getElementById('a'));
new p5(sketchB, document.getElementById('b'));
Each instance has its own mouseX, width, mousePressed(), etc., so the sketches never interfere.
Static Utilities Stay Intact
Classes like p5.Vector are still available as static members of the global p5 constructor, so vector math code written for global mode can be reused with no changes:
const v = p5.Vector.add(p5.Vector.random2D(), p5.Vector.random2D());
Trade‑offs and Ecosystem Friction
- **Code Translation** – Most tutorials, books, and community snippets assume global mode. Converting them to instance mode requires prefixing every call with the instance name (e.g.,
p.background()instead ofbackground()). - **Verbosity** – The syntax is a bit more verbose, which can be a hurdle for beginners or quick experiments.
- **Library Compatibility** – Some older add‑ons (e.g., the original
p5.soundorp5.serial) were written for global mode and may not work out of the box. Test them before relying on them.
Despite these caveats, instance mode is the recommended approach when you need a sketch to live inside a real website, especially if you plan to bundle, host multiple sketches, or avoid naming collisions.
How to Verify Your Decision
- Namespace Check – In a browser console, run
console.log(typeof window.ellipse)after loading a global‑mode sketch. It should return'function'. After switching to instance mode, run the same query; it should return'undefined'. - Multiple Sketch Test – Add two global‑mode sketches on a page and observe that the second overrides the first. Convert both to instance mode and confirm they render side by side.
- Bundler Test – Create a minimal Vite project, import p5, and write a sketch using global mode. It should not start. Switch to instance mode and confirm the canvas appears.
- Container Placement – Create a container
<div id="sketch1"></div>in your HTML. Pass its reference tonew p5()and verify the canvas is appended inside that div, not at the end ofbody.
When all these checks pass, you can confidently say instance mode is the right choice for your web‑integrated p5 sketches.
Conclusion
Instance mode is a stable, well‑supported feature of p5.js that solves the namespace and placement problems inherent in global mode. It fits naturally into modern JavaScript workflows and lets you run multiple, isolated sketches on a single page. The trade‑offs—some extra verbosity and a need to translate existing code—are minor compared to the benefits of clean, maintainable, and conflict‑free sketches.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.