js实现雨滴
实现雨滴效果的JavaScript代码
以下是一个使用HTML5 Canvas和JavaScript实现雨滴效果的完整示例代码:
// 获取Canvas元素和上下文
const canvas = document.getElementById('rainCanvas');
const ctx = canvas.getContext('2d');
// 设置Canvas尺寸为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 雨滴对象数组
const drops = [];
// 雨滴构造函数
function Drop() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height - canvas.height;
this.z = Math.random() * 0.5 + 0.5;
this.len = 10 * this.z;
this.speed = 5 * this.z;
this.opacity = Math.random() * 0.6 + 0.2;
}
// 初始化雨滴
for (let i = 0; i < 100; i++) {
drops.push(new Drop());
}
// 绘制雨滴
function draw() {
// 半透明背景实现拖尾效果
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制每个雨滴
drops.forEach(drop => {
ctx.beginPath();
ctx.moveTo(drop.x, drop.y);
ctx.lineTo(drop.x, drop.y + drop.len);
ctx.strokeStyle = `rgba(174, 194, 224, ${drop.opacity})`;
ctx.lineWidth = 1 * drop.z;
ctx.stroke();
// 更新雨滴位置
drop.y += drop.speed;
drop.x += 0.5 * drop.z; // 轻微倾斜效果
// 雨滴超出屏幕时重置
if (drop.y > canvas.height) {
drop.y = Math.random() * -100;
drop.x = Math.random() * canvas.width;
}
});
requestAnimationFrame(draw);
}
// 处理窗口大小变化
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// 开始动画
draw();
HTML结构
<!DOCTYPE html>
<html>
<head>
<title>雨滴效果</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="rainCanvas"></canvas>
<script src="raindrops.js"></script>
</body>
</html>
效果增强选项
-
添加溅起效果
当雨滴到达底部时可以添加小圆圈模拟溅起效果:
if (drop.y > canvas.height) { ctx.beginPath(); ctx.arc(drop.x, canvas.height, 2 * drop.z, 0, Math.PI * 2); ctx.fillStyle = `rgba(174, 194, 224, ${drop.opacity})`; ctx.fill(); drop.y = Math.random() * -100; drop.x = Math.random() * canvas.width; } -
调整雨滴密度
修改初始化时的雨滴数量(100)可以控制雨势大小。 -
添加闪电效果
可以随机触发白色闪光模拟闪电:
let lightning = false;
function draw() { if (Math.random() < 0.0005) { lightning = true; setTimeout(() => lightning = false, 100); }
ctx.fillStyle = lightning ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.05)'; ctx.fillRect(0, 0, canvas.width, canvas.height); // ...其余绘制代码 }
4. 性能优化
对于大量雨滴(>1000),可以考虑使用WebGL或粒子系统库如three.js来提高性能。






