js实现粒子特效
实现粒子特效的方法
使用JavaScript创建粒子特效可以通过Canvas或WebGL实现。以下是基于Canvas的简单粒子系统实现方法。
创建Canvas画布
在HTML中创建Canvas元素并获取2D渲染上下文:

<canvas id="particleCanvas"></canvas>
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
定义粒子类
创建一个粒子类,包含位置、速度、大小等属性:
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%)`;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.1;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
管理粒子系统
创建粒子数组和动画循环:

let particles = [];
function init() {
for (let i = 0; i < 100; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
particles.push(new Particle(x, y));
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle, index) => {
particle.update();
particle.draw();
if (particle.size <= 0.2) {
particles.splice(index, 1);
}
});
requestAnimationFrame(animate);
}
init();
animate();
添加交互效果
通过鼠标交互生成新粒子:
canvas.addEventListener('mousemove', (event) => {
for (let i = 0; i < 5; i++) {
particles.push(new Particle(event.x, event.y));
}
});
优化性能
对于大量粒子,使用对象池技术复用粒子对象:
const particlePool = [];
function getParticle(x, y) {
if (particlePool.length > 0) {
const particle = particlePool.pop();
particle.x = x;
particle.y = y;
particle.size = Math.random() * 5 + 1;
return particle;
}
return new Particle(x, y);
}
function recycleParticle(particle) {
particlePool.push(particle);
}
高级效果扩展
- 添加物理效果:实现重力、碰撞检测
- 纹理粒子:使用
drawImage替代圆形绘制 - 粒子轨迹:减少
clearRect的透明度实现拖尾效果 - 颜色渐变:动态改变粒子颜色
// 示例:重力效果
this.speedY += 0.1; // 在update方法中添加
以上方法提供了基础的粒子系统实现,可根据需求调整参数和扩展功能。对于更复杂的3D粒子效果,建议使用Three.js等WebGL库。






