Canvas 基础回顾
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 画一个圆
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.stroke();
涟漪效果的实现思路
- 用
requestAnimationFrame驱动动画循环 - 每个涟漪是一个对象:
{ x, y, radius, alpha, lineWidth } - 每帧
radius += speed,alpha -= 0.02,alpha 小于 0 时移除 - 多个涟漪同时存在,形成层叠效果
粒子系统的核心
每个粒子有位置、速度、加速度:
particles.push({
x: Math.random() * w,
y: Math.random() * h,
vx: (Math.random() - 0.5) * 2,
vy: (Math.random() - 0.5) * 2,
size: Math.random() * 3 + 1,
color: colors[Math.floor(Math.random() * colors.length)]
});
性能优化
- 用
offscreenCanvas做预渲染 - 粒子数量超过 500 时要有衰减机制
- 页面不可见时用
document.hidden暂停动画
