Javascript p5.js 类未正确绘制

标签 javascript class oop object 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

关于Javascript p5.js 类未正确绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54076215/

相关文章:

javascript - 如何在 Javascript 中比较密码

class - swift ios 委托(delegate)在多个类中同时运行

javascript - 如何从外部访问 React 类方法?

php - 同一文件中的类定义导致 fatal error

javascript - React.js 在获取完成之前渲染

javascript - 使用 jQuery 更改元素的 margin-right 值

javascript - 我有一个不断改变高度的 div。如何让第二个 div 不断采用第一个 div 的高度?

php - 所有用户中显示用户注销

java - 为什么继承的方法使用不重新定义的变量?

javascript - 嵌套私有(private)方法中的 OOP Javascript 'this' 关键字