javascript - 尝试理解并让类适用于 p5.js

标签 javascript class oop object p5.js

我正在尝试学习如何使用类来使我的代码可重用。我开始尝试创建一个背景类,当调用绘制方法时,该类应该生成背景,但目前这不会发生。请让我获得有关该类(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 。

最佳答案

发生了一些事情:

  • 正如 Sassel 所指出的,由于 a 在不同的地方被引用,因此需要在共享范围内定义它(例如,像全局变量一样)。
  • 此外,bg 应该是 draw 中的 this.bg。它也应该只初始化一次,因此可能应该将其移至构造函数中。看来传递的参数 diambg 并未实际使用,因此应将其删除。
  • beginShapeendShape 用于与 vertexcurveVertex 一起制作形状bezierVertexquadraticVertex 函数。由于您没有在这里执行此操作,因此没有必要。
  • 最后 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>

关于javascript - 尝试理解并让类适用于 p5.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54064270/

相关文章:

javascript - 引用数组中的对象时遇到问题

c++ - 在 C++ 类方法中使用 *this 完全覆盖自实例化

c++ - Student&a, Student&a; 之间的区别

javascript - 我可以从嵌套对象创建新的 Javascript 对象吗?

javascript - 如果找到类,如何为特定 Div 添加 css 属性(JQuery)

javascript - 在 igEditor 中输入基本元素时 listItems 不起作用

javascript - 如何使用多个键按对象的值对对象进行排序?

c++ - 使用默认构造函数初始化变量

c++ - 在构造函数 C++ 中初始化成员 vector

powershell - Powershell 5 中的类,需要帮助创建 $foo.bar.run()