Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Integrating p5.js via npm in Modern JavaScript Projects

Tech 3

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');
Tags: p5.jsnpmVite

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.