Integrating p5.js via npm in Modern JavaScript Projects
Initialize a new project using Vite with Vanila JavaScript:
npm create vite@latest
# Choose Vanilla and JavaScript
cd project-directory
npm install
Install the p5 library:
npm install p5
Importing p5 in an ES module environment requires a different approach compared to using a CDN. Global functions like setup() and draw() are unavailable becuase they are not bound to the window object. Directly calling p5.setup() will also result in an undefined error. Instead, use instance mode by passing a closure to the p5 constructor.
import p5 from 'p5';
let frameStep = 0;
const sketch = (p) => {
p.setup = () => {
p.createCanvas(500, 500);
p.background(40);
};
p.draw = () => {
const radius = p.abs(p.sin(frameStep)) * 150 + 50;
const centerX = p.width / 2;
const centerY = p.height / 2;
p.background(40);
p.fill(255, 100, 150);
p.noStroke();
p.ellipse(centerX, centerY, radius, radius);
frameStep += 0.05;
};
};
new p5(sketch);
By default, instantiating new p5(sketch) appends the generated canvas element to the end of the HTML body. To render the canvas inside a specific container, provide a second argument to the constructor representing the target element's ID or a direct DOM reference.
HTML structure:
<div id="app">
<h1>Header Content</h1>
<div id="canvas-container"></div>
<p>Footer Content</p>
</div>
<script type="module" src="/main.js"></script>
JavaScript implementation:
import p5 from 'p5';
const customSketch = (p) => {
p.setup = () => {
p.createCanvas(300, 300);
p.background(200);
};
};
// Mount to the element with id 'canvas-container'
new p5(customSketch, 'canvas-container');