Documentation Index
Fetch the complete documentation index at: https://mintlify.com/hetari/creative-coding/llms.txt
Use this file to discover all available pages before exploring further.
useP5 manages a p5.js sketch in instance mode, which isolates the p5 namespace inside a callback rather than polluting the global scope. You provide a sketch function that defines setup(), draw(), and any other p5 lifecycle methods; the composable handles the dynamic import of p5, constructs the instance bound to a container element, and calls p5.remove() on unmount — mirroring the exact teardown contract of usePixiApp.
Signature
Parameters
A Vue
TemplateRef or ShallowRef pointing to the container HTMLElement. The p5 canvas is created inside this element. If the ref is null when mountSketch is called, the function returns early without throwing.Return Value
A shallow reactive reference to the active p5 instance. The value is
null before mountSketch runs and after the component unmounts. Access p5 methods directly on p5.value when you need to interact with the instance imperatively outside the sketch function.Dynamically imports the p5 library, then constructs a new p5 instance in instance mode —
new P5(sketch, containerRef.value). If a previous instance already exists (e.g. on HMR), it is removed first via p5.remove() before the new one is created.Responsibilities
Owned by useP5 | Owned by the caller (your sketch) |
|---|---|
Dynamic import of p5 | Defining setup(), draw(), and lifecycle methods |
| Creating the p5 instance in instance mode | Loading assets and creating graphics |
| Binding the instance to the container element | Setting up user interactions |
Calling p5.remove() on unmount | Handling custom cleanup inside the sketch |
Usage Example
The following is taken from theshader/learn sketch, which uses useP5 to create a full-screen WEBGL canvas driven by GLSL shaders:
GLSL Shaders
Teardown
On component unmount,useP5 calls tryOnUnmounted (VueUse) to invoke p5.remove(), which stops the draw loop, removes the canvas from the DOM, and frees all p5-managed resources. The tryOnUnmounted variant keeps the teardown SSR-safe.