"Uncaught ReferenceError: window is not defined" p5.js web worker

"Uncaught ReferenceError: window is not defined" p5.js web worker

我有一个 javascript 代码,我在其中将 Web Worker 与 p5.js 库一起使用。它不允许我使用 p5 的任何功能,所以我必须在使用 p5 的任何功能之前使用 importScripts("p5.js") 函数导入 p5.js 库。

onmessage = (e)=>{
    importScripts("p5.min.js")
    // other scripts
}

但即便如此,它还是给了我另一个错误,说 “Uncaught ReferenceError: window is not defined”。我查了一下,好像是p5无法使用名为“window”的全局变量。我在互联网上搜索了解决方案,但到目前为止找到了 none。我想知道是否有办法解决这个问题。谢谢。

这里的问题是网络工作者 运行 在一个非常孤立的环境中,其中许多标准全局变量将存在于 javascript 运行 网站上(window、文档等)不存在,不幸的是 p5.js 无法在没有这些变量的情况下加载。您可以尝试用假版本填充它们。这是一个基本示例:

let loadHandlers = [];

window = {
  performance: performance,
  document: {
    hasFocus: () => true,
    createElementNS: (ns, elem) => {
      console.warn(`p5.js tryied to created a DOM element '${ns}:${elem}`);
      // Web Workers don't have a DOM
      return {};
    }
  },
  screen: {},
  addEventListener: (e, handler) => {
    if (e === "load") {
      loadHandlers.push(handler);
    } else {
      console.warn(`p5.js tried to added an event listener for '${e}'`);
    }
  },
  removeEventListener: () => {},
  location: {
    href: "about:blank",
    origin: "null",
    protocol: "about:",
    host: "",
    hostname: "",
    port: "",
    pathname: "blank",
    search: "",
    hash: ""
  }
};

document = window.document;
screen = window.screen;

// Without a setup function p5.js will not declare global functions
window.setup = () => {
  window.noCanvas();
  window.noLoop();
};

importScripts("/p5.js");

// Initialize p5.js
for (const handler of loadHandlers) {
  handler();
}

postMessage({ color: "green" });

onmessage = msg => {
  if (msg.data === "getRandomColor") {
    // p5.js places all of its global declarations on window
    postMessage({
      color: window.random([
        "red",
        "limegreen",
        "blue",
        "magenta",
        "yellow",
        "cyan"
      ])
    });
  }
};

这仅适用于 p5.js 函数的有限子集。任何绘制到 canvas 的函数肯定不会起作用。而且我会谨慎尝试来回传递对象(即 p5.Vector、p5.Color 等),因为通过 postMessage 发送的所有内容都会被序列化和反序列化。

我已经发布了这个示例的工作版本 on Glitch