如何将对象数组传递给 P5.js draw 函数



我在 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();
  }
}

您不会将参数传递到 draw() 函数中。draw()函数不接受任何参数。

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

var textToDisplay;
function setup(){
   createCanvas(500, 500);
   textToDisplay = "hello world";
}
function draw(){
   background(64);
   text(textToDisplay, 100, 100);
}

最新更新