如何将对象数组传递给P5.js绘图函数?
问题描述:
我已经在P5 setup()函数中创建了一个对象数组,并且可以毫无问题地绘制它们。但是,当我尝试在P5 draw()函数中绘制相同的对象时,它不起作用。如何将对象数组传递给P5.js绘图函数?
我猜这是因为我没有将对象传入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);
}
就是这样。我所要做的只是在setup()和draw()函数之外定义变量,并且我的草图可以正常工作。谢谢!!! – jpummill