简体   繁体   中英

How can I run user-input p5.js code in a React app?

I'm very familiar with p5.js, but brand new to web development. I've been getting familiar with React, and I'm working on building a React App that includes an in-browser p5 IDE. I am using Ace to build the code editor in a React Component without issue, but I'm not sure how to use that code to run a p5 sketch. This is my code so far:

import React from 'react';
import AceEditor from "react-ace";

import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-chrome"
import "ace-builds/src-noconflict/ext-language_tools";
import "ace-builds/webpack-resolver";

import p5 from 'p5';

import './App.css';


let inputCode='';

function onChange(newValue) {
  console.log(newValue);
  inputCode = newValue;
}

export class Editor extends React.Component {

  render() {
    return (
      <div className="container">
        <div className="title-container">
          <h1>p5 Code Editor</h1>
          <button>Run</button>
        </div>
        <AceEditor
          mode="javascript"
          width="100%"
          theme="chrome"
          onChange={onChange}
          name="UNIQUE_ID_OF_DIV"
          editorProps={{ $blockScrolling: true }}
        />
      </div>
    );
  }
}

export class Sketch extends React.Component {

  render() {
    return <div class="sketch-container" id="sketch-container"></div>
  }

}

All I've managed to do at this point beyond rendering the code editor is store the input code into a string. I know there are methods to evaluate stringified code (eval(), new Function()), but working in p5 seems to make it more complicated. The only examples I can find of using p5 in situations like this looks something like:

const s = (sketch) => {

  let x = 250;
  let y = 250;

  sketch.setup = () {
    sketch.createCanvas(500, 500);
  }
  sketch.draw = () {
    sketch.background(0);
    sketch.rect(x, y, 100, 100);
  }
  
}

let myp5 = new p5(s);

But if the user is coding in p5.js in the text editor, they shouldn't have to use the sketch.method() syntax whenever they want to use a function. So is there a way to translate input code written in p5.js into something readable in a React app? And if you can, how do you view the results within a specific div?

Instead of making the p5 code an actual React component, you could set up a designated file written in p5.js and write to it, and then run that code on a button press or whatever trigger you decide. Keep in mind that if you want to run it within a specific div you would need to add code to your setup function identifying that div.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM