-
Notifications
You must be signed in to change notification settings - Fork 69
Converting p5 functions for React
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.
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);
}
}
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 */
};
}