我正在尝试使用Javascript和HTML5 Canvas创建粒子效果,希望Canvas可以实现交互功能。也就是说,当用户在页面的特定区域单击时,它会生成一个随机速度、大小和颜色的粒子。该粒子将在屏幕上弹跳并持续弹跳,直到用户刷新页面。
祝好, 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 < 5; 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, false);
c.fill();
// Incrementing the X and Y postition
p.posX++;
p.posY++;
};
}
// Drawing the particle
window.requestAnimationFrame(draw);
<canvas id="canvas" width="1024" height="768">Your browser does not support HTML5 Canvas.</canvas>