Javascript p5.js класс не рисует правильно - PullRequest
0 голосов
/ 07 января 2019

Я создал класс 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();
            }
        }
    }
  }
}

Должно быть сгенерировано и показано одно безлистное дерево с несколькими ветвями

1 Ответ

0 голосов
/ 07 января 2019

В строке 40

имеется ошибка опечатки

Вместо this.blength = bLength; следует читать

this.bLength = bLength;

с большой буквы L

См. https://editor.p5js.org/HerrSerker/sketches/H17EDyWfV

...