我为树对象创建了一个javascript类,当调用.draw方法时,该程序应生成无叶树,但是目前该程序不断在彼此之间快速绘制单个分支树。
我仔细检查了该程序以尝试发现可能的错误,并寻找了可能有用的在线资源。我正在使用p5.js在线编辑器进行编程和检查代码,位于以下位置:https://editor.p5js.org
var a;
function setup() {
createCanvas(900, 700);
a = new createTree();
}
function draw() {
background(220);
a.draw();
}
class createTree {
constructor() {
this.tree = createGraphics(width, height);
this.n = 0;
}
draw() {
this.tree.beginShape();
this.tree.noStroke();
this.tree.background(0, 0);
for (this.i = 0; this.i < 3; this.i++) {
this.tree.fill(map(this.i, 0, 2, 60, 20));
this.branch(width / 2, height, 70, -HALF_PI, 150, 0);
}
this.tree.endShape();
image(this.tree, 0, 0);
}
branch(x, y, bSize, theta, bLength, pos) {
this.x = x;
this.y = y;
this.bSize = bSize;
this.theta = theta;
this.bLength = bLength;
this.pos = pos;
this.n += 0.01;
this.diam = lerp(this.bSize, 0.7 * this.bSize, this.pos / this.bLength);
this.diam *= map(noise(this.n), 0, 1, 0.4, 1.6);
this.tree.ellipse(this.x, this.y, this.diam, this.diam);
if (this.bSize > 0.6) {
if (this.pos < this.bLength) {
this.x += cos(this.theta + random(-PI / 10, PI / 10));
this.y += sin(this.theta + random(-PI / 10, PI / 10));
this.branch(this.x, this.y, this.bSize, this.theta, this.bLength, this.pos + 1);
} else {
this.drawLeftBranch = random(1) > 0.1;
this.drawRightBranch = random(1) > 0.1;
if (this.drawLeftBranch) this.branch(this.x, this.y, random(0.5, 0.7) * this.bSize, this.theta - random(PI / 15, PI / 5), random(0.6, 0.8) * this.bLength, 0);
if (this.drawRightBranch) this.branch(this.x, this.y, random(0.5, 0.7) * this.bSize, this.theta + random(PI / 15, PI / 5), random(0.6, 0.8) * this.bLength, 0);
if (!this.drawLeftBranch && !this.drawRightBranch) {
this.tree.push()
this.tree.translate(this.x, this.y);
this.tree.rotate(this.theta);
this.tree.quad(0, -this.diam / 2, 2 * this.diam, -this.diam / 6, 2 * this.diam, this.diam / 6, 0, this.diam / 2);
this.tree.pop();
}
}
}
}
}
应生成并显示具有多个分支的单个无叶树
答案 0 :(得分:1)
第40行出现错字错误
它应该代替this.blength = bLength;
读
this.bLength = bLength;
以大写字母L