[英]loop object over canvas JS P5
我使用JS P5。 我創建了一個創建橢圓的函數。 我想在整個畫布上循環這個橢圓,每個橢圓之間有一些距離。
我沒有使用普通橢圓,因為我想稍后在每個橢圓上放置另一個函數。 所以我的問題是如何在我創建的對象上使用 for 循環和嵌套循環。
這是我的代碼,我在這里有一個隨機的方式,但我想要的是確切的距離,就像整個頁面上的網格一樣。
像這個例子
let shapes = []; function setup() { createCanvas(600, 600); for (let i = 0; i < 500; i++){ let x = random(width); let y = random(height); shapes[i] = new shape(x,y,20); } } function draw() { background(220); for (let i = 0; i < shapes.length; i++){ shapes[i].display(); } } function shape(tx, ty, ts) { this.x = tx; this.y = ty; this.size = ts; this.angle = 0; this.update = function(mx, my) { this.angle = atan2(my - this.y, mx - this.x); }; this.display = function() { push(); fill(153, 204, 0); ellipse(this.x, this.y, this.size, this.size); pop(); }; }
編輯答案:
let shapes = [];
function setup() {
createCanvas(600, 600);
for(var x=0;x<width;x+=30){
for(var y=0;y<height;y+=30){
shapes.push(new shape(x,y,20));
}
}
}
function draw() {
background(220);
for (let i = 0; i < shapes.length; i++){
shapes[i].display();
}
}
function shape(tx, ty, ts) {
this.x = tx;
this.y = ty;
this.size = ts;
this.angle = 0;
this.update = function(mx, my) {
this.angle = atan2(my - this.y, mx - this.x);
};
this.display = function() {
push();
fill(153, 204, 0);
ellipse(this.x, this.y, this.size, this.size);
pop();
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.