在 canvas JS P5 上循环对象
loop object over canvas JS P5
我用的是JS P5。
我创建了一个创建椭圆的函数。
我想在整个 canvas 上循环此椭圆,每个椭圆之间有一定距离。
我没有使用普通的椭圆,因为我想稍后在每个椭圆上放置另一个函数。
所以我的问题是如何在我创建的对象上使用 for 循环和嵌套循环。
这是我的代码,我这里有一个随机的方式,但我想要的是准确的距离,就像整个页面上的网格。
像这样example
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();
};
}
我用的是JS P5。 我创建了一个创建椭圆的函数。 我想在整个 canvas 上循环此椭圆,每个椭圆之间有一定距离。
我没有使用普通的椭圆,因为我想稍后在每个椭圆上放置另一个函数。 所以我的问题是如何在我创建的对象上使用 for 循环和嵌套循环。
这是我的代码,我这里有一个随机的方式,但我想要的是准确的距离,就像整个页面上的网格。
像这样example
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();
};
}