我正在尝试学习如何使用类来使我的代码可重用。我开始尝试创建一个背景类,当调用绘制方法时,该类应该生成背景,但目前这不会发生。请让我获得有关该类(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
。它也应该只初始化一次,因此可能应该将其移至构造函数中。看来传递的参数diam
和bg
并未实际使用,因此应将其删除。 beginShape
和endShape
用于与vertex
、curveVertex
、一起制作形状bezierVertex
和quadraticVertex
函数。由于您没有在这里执行此操作,因此没有必要。- 最后 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/