You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React集成p5.js时重复渲染两个Canvas的问题求助

React 18 StrictMode 下 p5.js 重复渲染两个 Canvas 的问题

我在 React 中集成 p5.js 时遇到了重复渲染两个 Canvas 的问题。我知道关闭 StrictMode 可以解决,但希望保留严格模式的优势。我尝试过使用清理函数,但无论直接用 p5 库还是 react-p5 库都没效果。

相关代码

useP5.js

import p5 from "p5";
import { useEffect, useRef } from "react";

function useP5(sketch, dep) {
  const p5ref = useRef();

  useEffect(() => {
    const instance = new p5(sketch, p5ref.current);
    return instance.remove;
  }, [sketch, dep]);

  return p5ref;
}

export { useP5 };

App.js

import { useState } from "react";
import { useP5 } from "./hooks/useP5";

function App() {
  const sketch = (p) => {
    p.setup = () => {
      p.createCanvas(400, 400);
    };

    p.draw = () => {
      p.background(200);
      p.ellipse(50, 50, 50, 50);
    };
  };

  const p5Ref = useP5(sketch);

  return (
    <>
      <div ref={p5Ref}></div>
    </>
  );
}

export default App;

package.json

{
  "name": "unending-boundless-dream",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "p5": "^1.7.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

问题表现

本地开发环境下,只要开启 StrictMode 就会出现两个重叠的 Canvas,效果如下:
React与p5.js重复渲染的Canvas

但在线编辑器中测试时仅显示一个 Canvas,无法复现该问题。我需要找到在保留 StrictMode 的前提下,解决 p5.js 重复渲染 Canvas 的方法。


内容的提问来源于stack exchange,提问作者Alphatron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:55:10