我已经建立了一个由 3 组 3 个粒子组成的数组。我相信这与更改下面的代码部分有关。
> let particles;
> function init(){
> particles=[];
> for(let i=0; i<2;i+=1){
> for(var j=0; j<2;j+=1){
> particles.push(new Particle(centerX, centerY)); }
> console.log(particles);}
> console.log(particles);
> }
粒子当前位于相同位置。有没有办法将每个粒子的 x 和 y 方向的原点都移动 50?这是完整的代码:
window.onload =function(){
var canvas = document.createElement ("canvas");
c = canvas.getContext("2d");
canvas.width = 400;
canvas.height=400;
document.body.appendChild(canvas);
c.beginPath();
c.rect(0, 0, canvas.width, canvas.height);
c.fillStyle = "white";
c.fill();
c.closePath();
var centerX=canvas.width/2;
var centerY=canvas.width/2;
function Particle(centerX, centerY){
this.centerX=canvas.width/2;
this.centerY=canvas.width/2;
this.radians=0;
this.update=function(){
this.radians+=.1;
this.centerX=this.centerX+Math.sin(this.radians)*2;
this.centerY=this.centerY+Math.cos(this.radians)*2;
this.draw();
};
this.draw=function(){
c. beginPath();
c.arc(this.centerX,this.centerY,5,0,2*Math.PI);
c.fillStyle='black';
c.fill()
}
}
let particles;
function init(){
particles=[];
for(let i=0; i<2;i+=1){
for(var j=0; j<2;j+=1){
particles.push(new Particle(centerX, centerY));
}
}
}
function animate (){
requestAnimationFrame(animate);
c.beginPath();
c.rect(0, 0, canvas.width, canvas.height);
c.fillStyle = "white";
c.fill();
c.closePath();
particles.forEach(particle=>{
particle.update();
});
}
init();
animate();
}
谢谢
最佳答案
是的 - 我换行
this.centerX=canvas.width/2;
this.centerY=canvas.width/2;
至
this.centerX=centerX;
this.centerY=centerY;
和行particles.push(new Particle(centerX, centerY));
至
particles.push(new Particle(centerX+i*50, centerY+j*50));
(在 for
循环中,将 i<2
更改为 i<=2
,与 j 类似)运行代码片段并向下滚动以查看
window.onload =function(){
var canvas = document.createElement ("canvas");
c = canvas.getContext("2d");
canvas.width = 400;
canvas.height=400;
document.body.appendChild(canvas);
c.beginPath();
c.rect(0, 0, canvas.width, canvas.height);
c.fillStyle = "white";
c.fill();
c.closePath();
var centerX=canvas.width/2;
var centerY=canvas.width/2;
function Particle(centerX, centerY){
this.centerX=centerX;
this.centerY=centerY;
this.radians=0;
this.update=function(){
this.radians+=.1;
this.centerX=this.centerX+Math.sin(this.radians)*2;
this.centerY=this.centerY+Math.cos(this.radians)*2;
this.draw();
};
this.draw=function(){
c. beginPath();
c.arc(this.centerX,this.centerY,5,0,2*Math.PI);
c.fillStyle='black';
c.fill()
}
}
let particles;
function init(){
particles=[];
for(let i=0; i<=2;i+=1){
for(var j=0; j<=2;j+=1){
particles.push(new Particle(centerX+i*50, centerY+j*50));
}
}
}
function animate (){
requestAnimationFrame(animate);
c.beginPath();
c.rect(0, 0, canvas.width, canvas.height);
c.fillStyle = "white";
c.fill();
c.closePath();
particles.forEach(particle=>{
particle.update();
});
}
init();
animate();
}
关于javascript - 在 Javascript 中为对象数组创建不同的源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59116390/