Direct answer
Yes – a Global‑Mode p5.js add‑on can be used inside an Instance‑Mode sketch without editing its source, by temporarily binding the globals it expects to the methods of the p5 instance (or by passing the instance directly if the library already supports it).
Confirmed facts
- In Instance Mode the sketch function receives a p5 object (commonly named
p or sketch).
- Most official p5 add‑ons expose an initializer that accepts a p5 instance, e.g.
new MyLib(p5Inst) or MyLib.init(p5Inst).
- If a library only reads from
window (e.g. createCanvas, random), binding those properties to the instance makes the library behave as if it were running in Global Mode.
Likely explanation / pattern
- Create the p5 sketch in Instance Mode:
new p5(sketchFn, container) where sketchFn receives the instance.
- Inside
sketchFn, store the instance: const p5Inst = p;.
- Check whether the add‑on offers an init that takes a p5 object. If yes, call it directly:
new MyLib(p5Inst) (or MyLib.init(p5Inst)) and skip the binding step.
- If the library expects globals, wrap its construction in an IIFE that temporarily assigns the needed
window properties to the instance’s methods:
(function(p5){
// bind only the functions the library uses
window.createCanvas = p5.createCanvas.bind(p5);
window.random = p5.random.bind(p5);
// …add any other globals the library references…
// now the library runs as if in Global Mode
new MyLib(); // or MyLib.init()
// optional: clean up to avoid leaking
delete window.createCanvas;
delete window.random;
})(p5Inst);
Encapsulate the whole block in a dedicated wrapper module or IIFE so the temporary globals are scoped to the library’s execution and do not affect other sketches or page scripts.
Verification steps
- Load two independent Instance‑Mode sketches on the same page, each loading the same add‑on via the wrapper; open the console and confirm no errors and each sketch draws its own canvas.
- Inspect
window before and after the wrapper; verify any temporarily added properties are removed or restored.
Missing diagnostic detail: Does the specific add‑on expose an initialization function that accepts a p5 instance? If it does, you can skip the IIFE binding and simply pass the instance, which is safer and avoids any temporary window mutation.