P5JS 编辑器中有多个 Javascript 个草图?

Multiple Javascript Sketches in P5JS Editor?

我对 P5JS 和 P5JS 编辑器比较陌生。我也是 Stack Overflow 的新手。我正在尝试通过在编辑器中打开新选项卡将我的代码拆分为多个草图(.js 文件),如 'Coding Train' 视频中所述:https://www.youtube.com/watch?v=Yk18ZKvXBj4

我相信我准确地按照视频中的步骤进行了操作。我的 'index.html' 文件如下所示:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Untitled</title>
    <script src="libraries/p5.js" type="text/javascript"></script>

    <script src="libraries/p5.dom.js" type="text/javascript"></script>
    <script src="libraries/p5.sound.js" type="text/javascript"></script>

    <script src="sketch.js" type="text/javascript"></script>
    <script src="mybutton.js" type="text/javascript"></script>
    <script src="p5.collide2d.js" type="text/javascript"></script>

    <style> body {padding: 0; margin: 0;} canvas {vertical-align: top;} </style>
  </head>
  <body>
  </body>
</html>

我的目标是在我的程序中为一个名为 'MyButton' 的对象使用此函数:

function MyButton(xLoc, yLoc) {
  this.on = false;
  this.startXLoc = xLoc;
  this.startYLoc = yLoc;
  this.xLoc = xLoc;
  this.yLoc = yLoc;
  this.display = function() {
    if (this.on) {
      fill(255);
    } else {
      fill(100, 0, 0);
    }
    rect(this.xLoc, this.yLoc, 30, 30);
  }
}

并给它自己的文件,称为 'mybutton.js',使普通的 'sketch.js' 文件不那么混乱。目前,'sketch.js' 文件如下所示:

function setup() {
  createCanvas(windowWidth, windowHeight);
  rectMode(CENTER);
  noStroke();
}

var testButton = new MyButton(50, 50);  //This line produces the error
console.log(testButton);

function draw() {
  background(40);
  testButton.display();
}

然而,当我 运行 这样的代码时,我在第 7 行收到此错误:

7: Uncaught TypeError: Illegal constructor

而如果我 运行 在 'sketch.js' 文件中使用 'MyButton' 函数的代码(并且我没有给它自己的文件),它 运行s 正确,我完全没有错误。我不确定是什么问题。如何在没有任何错误的情况下为 'MyButton' 函数提供自己的文件?如果有什么不同的话,我是 运行ning P5JS on Linux Mint。任何帮助表示赞赏。谢谢!

如果你从 testButton 之前删除 var,那么错误就会减轻(像这样):

function setup() {
  createCanvas(windowWidth, windowHeight);
  rectMode(CENTER);
  noStroke();

  testButton = new MyButton(50, 50);  //This line produces the error
  console.log(testButton);

}

最初的问题是 p5js 需要在设置中声明的变量才能在绘制循环中访问它。从全局声明中删除 var 使得 testButton 非常类似于全局变量(但不完全)允许绘制循环到 "see" 变量。有关详细信息,请参阅 this 答案。