js实现粒子特效
实现粒子特效的基本步骤
创建粒子特效通常涉及初始化粒子、设置粒子行为、更新粒子状态和渲染粒子。以下是实现粒子特效的核心步骤。
初始化粒子系统
定义粒子对象的结构,包括位置、速度、大小、颜色和生命周期等属性。使用数组存储多个粒子实例。

class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.life = 100;
}
}
const particles = [];
for (let i = 0; i < 100; i++) {
particles.push(new Particle(canvas.width / 2, canvas.height / 2));
}
更新粒子状态
在每一帧更新粒子的位置和生命周期。移除生命周期结束的粒子,必要时添加新粒子。
function updateParticles() {
for (let i = 0; i < particles.length; i++) {
particles[i].x += particles[i].speedX;
particles[i].y += particles[i].speedY;
particles[i].life--;
if (particles[i].life <= 0) {
particles.splice(i, 1);
i--;
}
}
// 补充新粒子
if (particles.length < 100) {
particles.push(new Particle(canvas.width / 2, canvas.height / 2));
}
}
渲染粒子
使用Canvas API绘制粒子。根据粒子属性设置填充颜色和大小,绘制圆形或其他形状。

function drawParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const particle of particles) {
ctx.fillStyle = particle.color;
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
ctx.fill();
}
}
动画循环
使用requestAnimationFrame创建动画循环,持续更新和渲染粒子。
function animate() {
updateParticles();
drawParticles();
requestAnimationFrame(animate);
}
animate();
进阶优化技巧
添加重力、碰撞检测或粒子间的相互作用可以增强效果。使用WebGL或第三方库如Three.js能实现更复杂的3D粒子效果。
// 示例:添加重力
function updateParticles() {
for (let i = 0; i < particles.length; i++) {
particles[i].speedY += 0.1; // 重力加速度
particles[i].x += particles[i].speedX;
particles[i].y += particles[i].speedY;
particles[i].life--;
if (particles[i].life <= 0 || particles[i].y > canvas.height) {
particles.splice(i, 1);
i--;
}
}
}
通过调整粒子属性和行为规则,可以创建火焰、烟雾、雪花等不同特效。






