想要在网页中实现炫酷的粒子效果,HTML5 结合 JavaScript 是目前最常用且高效的方式。粒子动画可以用于背景装饰、交互反馈或数据可视化,提升用户体验。下面介绍如何用 HTML5 的 Canvas API 实现基础到进阶的粒子动画。
HTML5 的 canvas> 元素提供了一个绘图区域,通过 JavaScript 可以在上面绘制图形。粒子本质上是一个个小型图形(如圆点),不断更新位置形成动态效果。
基本步骤:
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor() {
this.x = Math.random() canvas.width;
this.y = Math.random() canvas.height;
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.05;
}
draw() {
ctx.fillStyle = '#00bfff';
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++) {
particles.push(new Particle());
}
}
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.2) {
particles.splice(i, 1);
i--;
particles.push(new Particle()); // 补充新粒子
}}
requestAnimationFrame(animate);
}
init();
animate();
3. 增强交互性:鼠标跟随与连接线
让粒子对用户行为产生反应,能大幅提升视觉吸引力。常见做法是让粒子向鼠标位置轻微移动,或在相近粒子间画线。
例如判断距离:
const dx = this.x - mouseX;
const dy = this.y - mouseY;
const distance = Math.sqrt(dx*dx + dy*dy);
if (distance < 100) {
this.x -= dx / 30;
this.y -= dy / 30;
}
粒子越多,性能消耗越大。合理优化能让动画在大多数设备上流畅运行。
比如设置半透明背景实现拖尾效果:
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'; ctx.fillRect(0, 0, canvas.width, canvas.height);
基本上就这些。掌握 Canvas 绘图和动画循环机制后,粒子效果并不复杂,但容易忽略细节如内存泄漏或过度重绘。合理设计生命周期和回收机制,才能做出既美观又稳定的动画。你可以在此基础上扩展颜色渐变、形状变化或响应音频等高级功能。