How to use React with p5.js

前端 未结 2 1213
温柔的废话
温柔的废话 2021-01-02 22:04

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

2条回答
  •  囚心锁ツ
    2021-01-02 22:59

    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 (
          
    ); } } 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.

提交回复
热议问题