I really like p5.js and react.js so i wondered how to combine these two together, and i was unable to do it so I need your help. I cant really provide you with some code sa
react-p5
This Component lets you integrate p5 Sketches into your React App. DEMO, Documentation
Installation
npm i react-p5
Usage
import React, { Component } from "react";
import Sketch from "react-p5";
export default class App extends Component {
x = 50
y = 50
setup = (p5, parent) => {
p5.createCanvas(500, 500).parent(parent)
}
draw = p5 => {
p5.background(0)
p5.ellipse(this.x, this.y, 70, 70)
this.x++
}
render() {
return <Sketch setup={this.setup} draw={this.draw} />
}
}
First thing that needs to be done is install the create-react-app tool. Once it's up and running the p5.js and the react-p5-wrapper packages can be included; assuming a package manager like npm is being used, this can be done by executing npm install p5 react-p5-wrapper
with whatever flags are considered necessary.
The react-p5-wrapper is a wrapper component that receives a reference (instance mode) to the sketch and uses some of the react component "lifecycle methods" to manipulate it accordingly, mainly by executing a method called myCustomRedrawAccordingToNewPropsHandler(props)
that needs to be defined within said sketch.
To give it a try and see it running, the contents of the App.js file could be modified like this:
import React, { Component } from 'react';
import P5Wrapper from 'react-p5-wrapper';
import sketch from './sketches/sketch';
import './App.css';
class App extends Component {
constructor(){
super();
this.state = {color:[Math.random()*255, Math.random()*255, Math.random()*255]};
this.randomColor = this.randomColor.bind(this);
}
randomColor(){
this.setState({color:[Math.random()*255, Math.random()*255, Math.random()*255]}
)
}
render() {
return (
<div>
<button onClick={this.randomColor}>Random Color</button>
<P5Wrapper sketch={sketch} color={this.state.color}></P5Wrapper>
</div>
);
}
}
export default App;
Where sketch
is imported from sketch.js which is located in another folder, in this case called sketches:
export default function sketch(p){
let canvas;
p.setup = () => {
canvas = p.createCanvas(300, 200);
p.noStroke();
}
p.draw = () => {
p.background('orangered');
p.ellipse(150, 100, 100, 100);
}
p.myCustomRedrawAccordingToNewPropsHandler = (newProps) => {
if(canvas) //Make sure the canvas has been created
p.fill(newProps.color);
}
}
If everything is working, a button and a sketch should be on screen and every time the button is pressed the circle in the sketch changes colors randomly.
It should be noted that the myCustomRedrawAccordingToNewPropsHandler
function is called in the componentDidMount
and the componentWillReceiveProps
"lifecycle methods" of the wrapper, the latter being currently classified as unsafe.