如何在具有 React 前端和 Express 后端的 Web 应用程序中使用 p5 SVG

问题描述 投票:0回答:1

我在 p5.js 中有一段代码使用基于 https://github.com/zenozeng/p5.js-svg 库的 SVG 画布。我有一个 React 前端,它应该绘制 p5.js 脚本的内容。现在出现的问题是 React 有标准 p5 库的包装器,如

react-p5-wrapper
react-use-p5
p5
;但它们不包括 SVG。所以问题是:

  • 如何在 React 前端运行 p5.js SVG 代码(我们可以绕过 React 吗?)
  • 否则,如何在 Express 后端的无头浏览器上运行 p5.js SVG 代码,然后将结果返回给前端。

p5.js SVG 示例代码:

function setup() {
    createCanvas(600, 200, SVG);  
}

function draw() {
    clear();
    fill('#ED225D');
    noStroke(); 
    ellipse(50, 50, 50, 50);
}
node.js reactjs express svg p5.js
1个回答
0
投票

这可能完全取决于您在 React 应用程序中使用的 p5.js 包装器,但从根本上说

p5.js-svg
应该可以正常工作。您可能会遇到的一个问题是让
p5.js-svg
在上下文中正确初始化,如果 p5 没有被全局导出(即包装器正在通过
p5
require()
导入
import
类型)。为了解决这个问题,您可能需要做一些额外的工作来在调用
p5.js-svg
之前初始化
createCanvas
(从
p5.js-svg
的默认导出是一个初始化函数,期望以
p5
类型作为参数调用) .但是,鉴于这适用于
react-p5
我认为您需要使用您正在使用的特定 p5.js 包装器包含一个最小的可重现示例。

这是一个使用

react-p5
呈现为 SVG 的组件示例:

import React from 'react';
import Sketch from 'react-p5';
// import p5 from 'p5';

// even though this import isn't used it is necessary because the p5.js-svg
// module auto-initializes so long as p5 is defined on window
import p5svg from 'p5.js-svg';

// Initialize p5.js-svg
// This isn't necessary because react-p5 exports the p5 type via window.p5
// p5svg(p5);

let x = 50;
let y = 50;

export default (props) => {
    const setup = (p, canvasParentRef) => {
        // use parent to render the canvas in this ref
        // (without that p5 will render the canvas outside of your component)
        p.createCanvas(500, 500, p.SVG).parent(canvasParentRef);
    };

    const draw = (p) => {
        p.background(0);
        p.fill(props.color || 'blue');
        p.ellipse(x % p.width, y, 70, 70);
        // NOTE: Do not use setState in the draw function or in functions that are executed
        // in the draw function...
        // please use normal variables or class properties for these purposes
        x++;
    };

    return <Sketch setup={setup} draw={draw} />;
};

注意:像使用

p5.js-svg
那样渲染动画是非常低效的。由于 p5.js 以即时模式绘制内容的性质,将动画渲染为 SVG(如果您不调用
background()
clear()
)存在很大的内存泄漏风险,甚至如果你这样做,那么整个 SVG 必须每帧重绘。因此,希望您将其与
noLoop()
一起使用来绘制不经常更改或不太复杂的东西。

© www.soinside.com 2019 - 2024. All rights reserved.