如何将对象数组传递给P5.js绘制函数?

时间:2017-10-28 22:40:58

标签: javascript p5.js

我在P5 setup()函数中创建了一个对象数组,可以毫无问题地绘制它们。但是,当我尝试在P5 draw()函数中绘制相同的对象时,它不起作用。

我猜这是因为我没有将对象传递给draw()方法,但是我遇到了问题,因为我不明白如何调用P5 draw()。

class Particle {
  constructor(x, y, size) {
    this.x = x;
    this.y = y;
    this.size = size;
  }

  display() {
    ellipse(this.x, this.y, this.size, this.size); 
  }
}

function setup() {

  var screenWidth = 720;
  var screenHeight = 480;
  var numberOfParticles = 10;

  var particles = [];

  for (var idx = 0; idx < numberOfParticles; idx++) {
    size = Math.floor(Math.random() * 40) + 10;
    x = Math.floor(Math.random() * (screenWidth - (size * 2))) + size;
    y = Math.floor(Math.random() * (screenHeight - (size * 2))) + size;
    var p = new Particle(x, y, size);
    particles.push(p);
  }

  createCanvas(screenWidth,screenHeight);

  background(100,150,200);
  fill("yellow");

  // This displays the particles
  for (var idx = 0; idx < particles.length; idx++) {
    particles[idx].display();
  }

}

function draw() {
  fill("green");

  // This DOESN'T display the particles
  for (var idx = 0; idx < particles.length; idx++) {
    particles[idx].display();
  }

}

1 个答案:

答案 0 :(得分:0)

您不会将参数传递给draw()函数。 draw()函数不带任何参数。

相反,只需定义两个函数之外的变量。然后,您可以在setup()函数中初始化,并在draw()函数中使用它。像这样:

var textToDisplay;

function setup(){
   createCanvas(500, 500);
   textToDisplay = "hello world";
}

function draw(){
   background(64);
   text(textToDisplay, 100, 100);
}