试图理解并让 类 为 p5.js 工作

Trying to understand and get classes to work for p5.js

我正在尝试学习如何使用 classes 使我的代码可重用。我已经开始尝试创建一个背景 class ,当调用 draw 方法时,它应该生成一个背景,但是目前这并没有发生。请给我关于 class 的反馈以及我在使用它时犯的任何错误。

使用在线资源,我尝试根据函数设置后台class,如代码所示。我正在使用在线 p5.js 编辑器进行编码,可在此处找到:https://editor.p5js.org

function setup() {
  createCanvas(900, 700);
  const a = new treeBackground(1,1)

}

function draw() {
  a.draw()
}

class treeBackground {

  constructor(bg, diam) {
    this.bg = bg;
    this.diam = diam;
  }

  draw() {
    this.bg = createGraphics(width, height);
    this.bg.beginShape();
    this.bg.noStroke();
    for (this.diam = 1.5 * width; this.diam > 0.5 * width; this.diam -= 20) {
        bg.fill(map(this.diam, 0.5 * width, 1.5 * width, 255, 210));
        bg.ellipse(width / 2, height / 2, this.diam, this.diam);
    }
    this.bg.endShape();

  }

}

不应出现任何错误,草图区域中应显示带有灰色背景的 canvas。

发生了一些事情:

  • 正如 saucel 指出的那样,由于 a 在不同的地方被引用,它需要在共享范围内定义(例如像全局变量一样)。
  • 另外 bgdraw 中应该是 this.bg。它也应该只初始化一次,所以它可能应该移到构造函数中。看起来传递的参数 diambg 并未实际使用,因此应将其删除。
  • beginShapeendShapevertexcurveVertexbezierVertexquadraticVertex 函数一起用于制作形状.由于您在这里不这样做,因此没有必要。
  • 最后 createGraphics 创建了一个离屏渲染器。要在屏幕上实际显示它,您可以使用 image 函数。

加在一起,看起来像这样:

var a;
function setup() {
  createCanvas(900, 700);
  a = new treeBackground();
}

function draw() {
  a.draw();
}

class treeBackground {

  constructor() {
    this.bg = createGraphics(width, height);
  }

  draw() {
    this.bg.noStroke();
    for (this.diam = 1.5 * width; this.diam > 0.5 * width; this.diam -= 20) {
        this.bg.fill(map(this.diam, 0.5 * width, 1.5 * width, 255, 110)); // changed this to make the gradient more pronounced
        this.bg.ellipse(width / 2, height / 2, this.diam, this.diam);
    }
    image(this.bg, 0, 0);
  }

}
<script src="https://unpkg.com/p5@0.7.2/lib/p5.min.js"></script>