效果说明
本案例实现了一个简单的下雨动画效果。通过创建多个雨滴对象,模拟自然的降雨场景。每个雨滴都有独立的速度和长度,形成错落有致的视觉效果。
核心实现
1. 雨滴对象设计
每个雨滴都是一个独立的对象,包含位置、速度和长度等属性:
class Raindrop {
constructor() {
this.x = Math.random() * canvas.width; // 随机水平位置
this.y = -10; // 从顶部开始
this.speed = 5 + Math.random() * 10; // 随机速度
this.length = 10 + Math.random() * 20; // 随机长度
}
}
2. 雨滴运动原理
雨滴采用简单的线性运动,通过不断更新垂直位置实现下落效果:
update() {
this.y += this.speed; // 位置 = 当前位置 + 速度
if (this.y > canvas.height) {
this.reset(); // 超出画布底部时重置
}
}
3. 拖尾效果实现
通过绘制半透明背景层实现雨滴拖尾:
ctx.fillStyle = 'rgba(26, 26, 26, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
扩展思路
- 添加风向效果(给雨滴添加水平速度)
- 实现雨滴碰撞效果
- 添加雨滴积累效果
- 实现交互式控制雨量