js实现粒子特效
实现粒子特效的基本步骤
创建Canvas元素并初始化上下文。在HTML中添加Canvas标签,通过JavaScript获取该元素并设置其宽高以适应屏幕。
<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;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.1;
}
draw() {
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
管理粒子数组
创建粒子数组并实现添加新粒子的逻辑。通常根据鼠标移动或时间间隔生成新粒子。
let particles = [];
function createParticles(x, y) {
for (let i = 0; i < 5; i++) {
particles.push(new Particle(x, y));
}
}
window.addEventListener('mousemove', (e) => {
createParticles(e.clientX, e.clientY);
});
动画循环实现
使用requestAnimationFrame创建动画循环,在每一帧中更新和绘制所有粒子,并移除过小的粒子。
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
if (particles[i].size <= 0.3) {
particles.splice(i, 1);
i--;
}
}
requestAnimationFrame(animate);
}
animate();
增强特效效果
添加连线功能使相近粒子之间产生连接线,增强视觉效果。计算粒子间距离,当距离小于阈值时绘制线段。
function connectParticles() {
for (let a = 0; a < particles.length; a++) {
for (let b = a; b < particles.length; b++) {
const dx = particles[a].x - particles[b].x;
const dy = particles[a].y - particles[b].y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 100) {
ctx.strokeStyle = `rgba(255, 255, 255, ${1 - distance/100})`;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(particles[a].x, particles[a].y);
ctx.lineTo(particles[b].x, particles[b].y);
ctx.stroke();
}
}
}
}
在animate函数中调用connectParticles()即可实现连线效果。
响应窗口大小变化
添加事件监听器,在窗口大小改变时调整Canvas尺寸。
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
优化性能
对于大量粒子,使用对象池技术重用粒子对象而非频繁创建销毁。设置最大粒子数量限制防止性能下降。
const MAX_PARTICLES = 1000;
function createParticles(x, y) {
if (particles.length < MAX_PARTICLES) {
for (let i = 0; i < 5; i++) {
particles.push(new Particle(x, y));
}
}
}






