【问题标题】:p5.js not recognizing code in other filesp5.j​​s 无法识别其他文件中的代码
【发布时间】:2021-03-29 09:00:22
【问题描述】:

在 p5.js 项目中使用 VSCode。在一个文件中,我创建了一个blob 类并给它一个createVector 函数,然后在sketch.js 中创建blob 的一个实例并在function setup() 中调用blob.createVector()。由于某种原因,它完全崩溃并且控制台日志:

Uncaught (in promise) ReferenceError: createVector is not defined
    at new Blob (blob.js:2)
    at p5.sound.min.js:2
    at Array.map 

文件结构:

|-- blob.js
|-- index.html
|-- jsconfig.json
|-- libraries
|   |-- p5.min.js
|   |-- p5.sound.min.js
|-- sketch.js
|-- style.css

sketch.js:

var blob;

function setup() {
  blob = new Blob();
  createCanvas(600, 600);
}

function draw() {
  background(0);
  blob.show();
}

blob.js:

function Blob() {
  this.pos = createVector(width/2, height/2);
  this.r = 64;

  this.show = function() {
    fill(255);
    ellipse(this.pos.x, this.pos.y, this.r*2, this.r*2);
  }
}

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script src="libraries/p5.min.js"></script>
    <script src="libraries/p5.sound.min.js"></script>
  </head>

  <body>
    <script src="sketch.js"></script>
    <script src="blob.js"></script>
  </body>
</html>

【问题讨论】:

    标签: javascript html canvas processing p5.js


    【解决方案1】:

    问题是您在创建 blob 之后创建画布,并且在构造函数中,您使用的是在创建画布时初始化的 widht 和 height 属性。这意味着您唯一需要做的就是按以下方式更改顺序:

    var blob;
    
    function setup() {
      createCanvas(600, 600);
      blob = new Blob();
      
    }
    
    function draw() {
      
      background(0);
      blob.show();
    }
    
    class Blob{
      
      constructor(){
        this.pos = createVector(width/2, height/2);
        this.r = 64;
      }
    
      show(){
        fill(255);
        ellipse(this.pos.x, this.pos.y, this.r*2, this.r*2);
      }
    }
    

    如果你检查this site,你会发现你的类构造方法有点过时了。我会尝试按照这里的方式进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多