效果说明
本案例实现了一个鼠标点击时的粒子爆发效果。粒子会以点击位置为中心向四周散开,并受重力影响逐渐下落,同时颜色和透明度也会随时间变化。
核心实现
1. 粒子类设计
每个粒子都包含位置、速度、生命值等属性:
class Particle {
constructor(x, y) {
// 位置
this.x = x;
this.y = y;
// 运动参数
this.speedX = (Math.random() - 0.5) * 8; // 随机水平速度
this.speedY = (Math.random() - 0.5) * 8; // 随机垂直速度
this.gravity = 0.1; // 重力加速度
// 外观
this.size = Math.random() * 3 + 2; // 随机大小
this.color = `hsl(${Math.random() * 360}, 100%, 60%)`; // 随机颜色
// 生命周期
this.life = 1; // 生命值
this.decay = 0.02; // 衰减速度
}
}
2. 物理运动模拟
实现了三种物理效果:
update() {
// 1. 重力效果
this.speedY += this.gravity;
// 2. 空气阻力
this.speedX *= 0.99;
this.speedY *= 0.99;
// 3. 位置更新
this.x += this.speedX;
this.y += this.speedY;
}
3. 轨迹效果实现
通过半透明背景叠加实现轨迹:
function animate() {
// 关键: 使用半透明背景
ctx.fillStyle = 'rgba(26, 26, 26, 0.2)'; // 透明度0.2
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 更新和绘制粒子
particles = particles.filter(particle => {
particle.update();
particle.draw();
return particle.life > 0;
});
}
透明度说明:
- 值越小(如0.1): 轨迹更长,消失更慢
- 值越大(如0.3): 轨迹更短,消失更快
- 0.2是一个比较平衡的值