Skip to content
This repository has been archived by the owner on Jun 29, 2020. It is now read-only.

Converting p5 functions for React

lucierabahi edited this page Jul 22, 2019 · 1 revision

Classic p5 sketches should be enclosed in a function that takes a parameter p. This parameter will be used to access p5 functions.

p5-wrapper also requires the p5 package so you need to make sure that it is also installed in your React application.

Once your initial p5 sketch is enclosed in a function, you need to convert your function declarations as function expressions. The variables used to hold the converted functions should be within the scope of the parameter.

You can use myCustomRedrawAccordingToNewPropsHandler function that takes props as a parameter to change the values/call functions when states are changed in React.

Lastly, you need to export the function that was used to enclosed your initial p5 sketch file. By doing this, you can import it to the component where you will use the p5-wrapper and pass the function as a props for sketch.

Example:

p5 sketch file:

function setup() {
  // Create the canvas
  createCanvas(720, 400);
  background(200);

  // Set colors
  fill(204, 101, 192, 127);
  stroke(127, 63, 120);

  // A rectangle
  rect(40, 120, 120, 40);
  // An ellipse
  ellipse(240, 240, 80, 80);
  // A triangle
  triangle(300, 100, 320, 100, 310, 80);

  // A design for a simple flower
  translate(580, 200);
  noStroke();
  for (let i = 0; i < 10; i ++) {
    ellipse(0, 30, 20, 80);
    rotate(PI/5);
  }
}

Converted for React use

export default function sketch (p) {

    p.setup = function () {
        // Create the canvas
        p.createCanvas(720, 400);
        p.background(200);

        // Set colors
        p.fill(204, 101, 192, 127);
        p.stroke(127, 63, 120);

        // A rectangle
        p.rect(40, 120, 120, 40);
        // An ellipse
        p.ellipse(240, 240, 80, 80);
        // A triangle
        p.triangle(300, 100, 320, 100, 310, 80);

        // A design for a simple flower
        p.translate(580, 200);
        p.noStroke();

        for (let i = 0; i < 10; i ++) {
        p.ellipse(0, 30, 20, 80);
        p.rotate(Math.PI/5);
        }
    }

    p.myCustomRedrawAccordingToNewPropsHandler = function (props) {
        /* Listen for props changes here */
      };
}