Как вы перерисовываете объект, созданный из класса в j5.ascript p5.js

1

У меня есть класс, который рисует дерево, однако я хотел бы иметь возможность рисовать другое дерево, когда мышь нажата, однако я не могу в настоящее время как redraw(); просто добавляет дерево поверх текущего холста. Я хотел бы иметь возможность рисовать новое дерево каждый клик.

Я попытался найти способ удаления объектов или сброса атрибутов класса, однако мне это не удалось. Я использовал редактор p5.js и приведенный ниже код можно найти здесь: https://editor.p5js.org/remcqueen/sketches/Sk0smd8G4

var a;

function setup() {
  createCanvas(600, 600);
  a = new clCreateTree();
}

function draw() {
  noLoop();
  background(220);
  a.draw();
}

function mousePressed() {
  redraw();

}

class clCreateTree {

  constructor() {
    this.tree = createGraphics(width, height);
    this.n = 0;
    this.leafs = [];
    this.treeHeight = 150;
    this.treeDensity = 3;
    this.treeAge = 70;
  }

  sketch() {
    this.tree.beginShape();
    this.tree.noStroke();
    this.tree.background(0, 0);

    for (var i = 0; i < this.treeDensity; i++) {
        this.tree.fill(map(i, 0, 2, 60, 20));
        this.branch(width/2, height, this.treeAge, -HALF_PI, this.treeHeight, 0);
    }
    this.tree.endShape();
  }

  draw() {
    this.sketch();
    image(this.tree, 5, 5);

  }


  branch(x, y, bSize, theta, bLength, pos) {

    this.n += 0.01;
    var diam = lerp(bSize, 0.7 * bSize, pos / bLength);
    diam *= map(noise(this.n), 0, 1, 0.4, 1.6);

    this.tree.ellipse(x, y, diam, diam);
    if (bSize > 0.6) {
        if (pos < bLength) {
            x += cos(theta + random(-PI / 10, PI / 10));
            y += sin(theta + random(-PI / 10, PI / 10));
            this.branch(x, y, bSize, theta, bLength, pos + 1);
        } else {
            this.leafs.push(createVector(x, y));
            var drawLeftBranch = random(1) > 0.1;
            var drawRightBranch = random(1) > 0.1;
            if (drawLeftBranch) this.branch(x, y, random(0.5, 0.7) *  bSize, theta - random(PI / 15, PI / 5), random(0.6, 0.8) * bLength, 0);
            if (drawRightBranch) this.branch(x, y, random(0.5, 0.7) * bSize, theta + random(PI / 15, PI / 5), random(0.6, 0.8) * bLength, 0);

            if (!drawLeftBranch && !drawRightBranch) {
                this.tree.push()
                this.tree.translate(x, y);
                this.tree.rotate(theta);
                this.tree.quad(0, -diam / 2, 2 * diam, -diam / 6, 2 * diam, diam / 6, 0, diam / 2);
                this.tree.pop();
            }
        }
     }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

Ожидаемый результат должен состоять в том, что при нажатии мыши новое дерево рисуется без какого-либо перекрытия, которое происходит в данный момент.

Теги:
class
object
p5.js
processing
redraw

1 ответ

0

Вы должны clear() графический объект, прежде чем рисовать дерево:

sketch() {
    this.tree.beginShape();
    this.tree.clear(); // <--- clear
    this.tree.noStroke();

    for (var i = 0; i < this.treeDensity; i++) {
        this.tree.fill(map(i, 0, 2, 60, 20));
        this.branch(width/2, height, this.treeAge, -HALF_PI, this.treeHeight, 0);
    }
    this.tree.endShape();
}

Или вы должны нарисовать сплошной фон (альфа = 255), прежде чем нарисовать дерево:

sketch() {
    this.tree.beginShape();

    this.tree.noStroke();
    this.tree.background(255,255);

    for (var i = 0; i < this.treeDensity; i++) {
        this.tree.fill(map(i, 0, 2, 60, 20));
        this.branch(width/2, height, this.treeAge, -HALF_PI, this.treeHeight, 0);
    }
    this.tree.endShape();
}

var a;

function setup() {
  createCanvas(600, 600);
  a = new clCreateTree();
}

function draw() {
  noLoop();
  background(220);
  a.draw();
}

function mousePressed() {
  redraw();

}

class clCreateTree {

  constructor() {
    this.tree = createGraphics(width, height);
    this.n = 0;
    this.leafs = [];
    this.treeHeight = 150;
    this.treeDensity = 3;
    this.treeAge = 70;
  }

  sketch() {
    this.tree.beginShape();
    this.tree.clear();
    this.tree.noStroke();

    for (var i = 0; i < this.treeDensity; i++) {
        this.tree.fill(map(i, 0, 2, 60, 20));
        this.branch(width/2, height, this.treeAge, -HALF_PI, this.treeHeight, 0);
    }
    this.tree.endShape();
  }

  draw() {
    this.sketch();
    image(this.tree, 5, 5);

  }


  branch(x, y, bSize, theta, bLength, pos) {

    this.n += 0.01;
    var diam = lerp(bSize, 0.7 * bSize, pos / bLength);
    diam *= map(noise(this.n), 0, 1, 0.4, 1.6);

    this.tree.ellipse(x, y, diam, diam);
    if (bSize > 0.6) {
        if (pos < bLength) {
            x += cos(theta + random(-PI / 10, PI / 10));
            y += sin(theta + random(-PI / 10, PI / 10));
            this.branch(x, y, bSize, theta, bLength, pos + 1);
        } else {
            this.leafs.push(createVector(x, y));
            var drawLeftBranch = random(1) > 0.1;
            var drawRightBranch = random(1) > 0.1;
            if (drawLeftBranch) this.branch(x, y, random(0.5, 0.7) *  bSize, theta - random(PI / 15, PI / 5), random(0.6, 0.8) * bLength, 0);
            if (drawRightBranch) this.branch(x, y, random(0.5, 0.7) * bSize, theta + random(PI / 15, PI / 5), random(0.6, 0.8) * bLength, 0);

            if (!drawLeftBranch && !drawRightBranch) {
                this.tree.push()
                this.tree.translate(x, y);
                this.tree.rotate(theta);
                this.tree.quad(0, -diam / 2, 2 * diam, -diam / 6, 2 * diam, diam / 6, 0, diam / 2);
                this.tree.pop();
            }
        }
     }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню