我试图在屏幕上显示粒子,然后以某种方式对其进行动画处理。就像在屏幕上四处走动一样。我找不到无法显示这些粒子的错误。
最好的问候, Tar2ed
// Initializing the canvas
var canvas = document.getElementById("canvas");
var c = canvas.getContext('2d');
// Setting the positition in the middle of the canvas
var posX = 512,
posY = 384;
// Creation of an array of particles
var particles = [];
for (var i = 0; i < 50; i++) {
particles.push(new Particle());
}
// Creation of a fucntion which will help us create multiple particles
function Particle() {
// Randomizing the position on the canvas
this.posX = Math.random() * canvas.width;
this.posY = Math.random() * canvas.height;
}
// Creating a draw function
function draw() {
// Painting the canvas in black
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var d = 0; d < Particle.length; d++) {
var p = particles[d];
// Creating the particle
c.beginPath();
c.fillStyle = "white";
c.arc(p.posX, p.posY, 5, Math.PI * 2, false);
c.fill();
// Incrementing the X and Y postition
p.posX++;
p.posY++;
};
}
// Drawing the particle
setInterval(draw, 33);
<canvas id="canvas"></canvas>
答案 0 :(得分:2)
Particle.length
应该为particles.length
。c.arc
的参数错误。它们应该是:c.arc(p.posX, p.posY, 5, 0, Math.PI * 2);
window.requestAnimationFrame()
来调用绘制循环。示例中的演示
// Initializing the canvas
var canvas = document.getElementById("canvas");
var c = canvas.getContext('2d');
// Setting the positition in the middle of the canvas
var posX = 512,
posY = 384;
// Creation of an array of particles
var particles = [];
for (var i = 0; i < 50; i++ ){
particles.push(new Particle());
}
// Creation of a fucntion which will help us create multiple particles
function Particle() {
// Randomizing the position on the canvas
this.posX = Math.random() * canvas.width;
this.posY = Math.random() * canvas.height;
}
// Creating a draw function
function draw() {
// Painting the canvas in black
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var d = 0; d < particles.length; d++) {
var p = particles[d];
// Creating the particle
c.beginPath();
c.fillStyle = "white";
c.arc(p.posX, p.posY, 5, 0, Math.PI * 2);
c.fill();
// Incrementing the X and Y postition
p.posX++;
p.posY++;
}
}
// Drawing the particle
setInterval(draw, 33);
<canvas id="canvas" width="310" height="160">