0
我已經在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();
}
}
就是這樣。我所要做的只是在setup()和draw()函數之外定義變量,並且我的草圖可以正常工作。謝謝!!! – jpummill