js实现雨滴
实现雨滴效果的JavaScript方法
使用HTML5 Canvas和JavaScript可以轻松创建雨滴效果。以下是一个简单的实现方法:
const canvas = document.getElementById('rainCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rainDrops = [];
const rainCount = 100;
class RainDrop {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * -canvas.height;
this.speed = 2 + Math.random() * 5;
this.length = 10 + Math.random() * 20;
this.opacity = Math.random() * 0.6;
}
update() {
this.y += this.speed;
if (this.y > canvas.height) {
this.y = Math.random() * -100;
this.x = Math.random() * canvas.width;
}
}
draw() {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x, this.y + this.length);
ctx.strokeStyle = `rgba(174, 194, 224, ${this.opacity})`;
ctx.lineWidth = 1;
ctx.stroke();
}
}
for (let i = 0; i < rainCount; i++) {
rainDrops.push(new RainDrop());
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
rainDrops.forEach(drop => {
drop.update();
drop.draw();
});
requestAnimationFrame(animate);
}
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
HTML结构
需要在HTML中添加canvas元素:
<!DOCTYPE html>
<html>
<head>
<title>雨滴效果</title>
<style>
body { margin: 0; overflow: hidden; background: #1a1a2e; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="rainCanvas"></canvas>
<script src="raindrops.js"></script>
</body>
</html>
效果增强选项
可以通过修改参数来增强雨滴效果:

增加雨滴数量:
const rainCount = 200; // 改为更大的数字
添加重力效果:

this.speed += 0.05; // 在update方法中添加
创建溅射效果:
if (this.y > canvas.height - 10) {
this.speed = 0;
this.length -= 0.2;
if (this.length < 0) {
this.y = Math.random() * -100;
this.x = Math.random() * canvas.width;
this.speed = 2 + Math.random() * 5;
this.length = 10 + Math.random() * 20;
}
}
性能优化
对于大量雨滴,可以使用对象池技术:
// 对象池实现
const rainPool = [];
const POOL_SIZE = 300;
function createRainDrop() {
if (rainPool.length < POOL_SIZE) {
return new RainDrop();
}
const drop = rainPool.shift();
drop.x = Math.random() * canvas.width;
drop.y = Math.random() * -100;
drop.speed = 2 + Math.random() * 5;
drop.length = 10 + Math.random() * 20;
drop.opacity = Math.random() * 0.6;
return drop;
}
function recycleDrop(drop) {
rainPool.push(drop);
}






