Javascript p5.js类绘制不正确



我为树对象创建了一个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();
            }
        }
    }
  }
}

应生成并显示具有多个分支的单个无叶树

第 40 行有拼写错误

而不是this.blength = bLength;它应该读

this.bLength = bLength;

有资本L

见 https://editor.p5js.org/HerrSerker/sketches/H17EDyWfV

最新更新