p5js with react code example
Example 1: combine p5 with react
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)
p.fill(newProps.color);
}
}
Example 2: combine p5 with react
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;