Skip to content

P5.js Integration API

Propa offers a helper function to easily embed p5.js sketches into your application.

createP5Sketch(props: P5Props): HTMLElement

Creates an HTML element that hosts a p5.js sketch and manages its lifecycle.

  • props: An object with the following properties:
    • sketch: (p: p5) => void: Your p5.js sketch function. This function receives a p5 instance (p) and should contain your p.setup(), p.draw(), and other p5 event handlers.
    • containerClass?: string (optional): CSS class(es) to apply to the div container that hosts the p5 canvas.
    • containerStyle?: string (optional): Inline CSS styles to apply to the container div.
  • Returns: An HTMLElement (specifically, a div) that will contain the p5.js canvas.

P5Props Interface

typescript
interface P5Props {
    sketch: (p: p5) => void;
    containerStyle?: string;
    containerClass?: string;
}

Usage

The createP5Sketch function handles the creation of the p5 instance when the host component is mounted and calls p5Instance.remove() when the component is unmounted, ensuring proper cleanup.

tsx
import { h, createP5Sketch } from '@salernoelia/propa';
import p5 from 'p5'; // Ensure p5 is installed

const MySketchComponent = () => {
  const sketchSetup = (p: p5) => {
    p.setup = () => {
      p.createCanvas(200, 200);
      p.background(0);
    };

    p.draw = () => {
      p.fill(255, p.frameCount % 255, 0);
      p.ellipse(p.width / 2, p.height / 2, 50, 50);
    };
  };

  return createP5Sketch({
    sketch: sketchSetup,
    containerClass: 'p5-container',
    containerStyle: 'border: 1px solid red;'
  });
};

// Use in another component:
// const App = () => <div><MySketchComponent /></div>;

This function leverages ComponentLifecycle internally to manage the p5.js instance.

Released under the MIT License.