css制作下雨动画
使用CSS制作下雨动画
通过CSS的@keyframes和animation属性可以模拟下雨效果。以下是一个简单实现方法:
HTML结构
<div class="rain"></div>
CSS动画

.rain {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
}
.rain:before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 2px;
height: 10px;
background: linear-gradient(transparent, #00b4ff);
animation: rain-fall 1s linear infinite;
}
@keyframes rain-fall {
0% {
transform: translateY(-100px) rotate(15deg);
opacity: 1;
}
100% {
transform: translateY(100vh) rotate(15deg);
opacity: 0.2;
}
}
增强雨滴效果
创建多个随机分布的雨滴:
.rain span {
position: absolute;
width: 2px;
height: 10px;
background: #00b4ff;
animation: rain 1s linear infinite;
}
@keyframes rain {
to {
transform: translateY(100vh);
}
}
通过JavaScript动态生成雨滴:

const rainContainer = document.querySelector('.rain');
for(let i=0; i<100; i++) {
const drop = document.createElement('span');
drop.style.left = Math.random() * 100 + 'vw';
drop.style.animationDuration = (Math.random() * 0.5 + 0.5) + 's';
drop.style.opacity = Math.random();
rainContainer.appendChild(drop);
}
添加雨滴溅起效果
使用伪元素模拟雨滴落地效果:
.rain span:after {
content: '';
position: absolute;
bottom: -5px;
left: -1px;
width: 4px;
height: 2px;
background: rgba(255,255,255,0.2);
border-radius: 50%;
animation: splash 0.4s ease-out infinite;
}
@keyframes splash {
0% {
transform: scale(1);
opacity: 1;
}
100% {
transform: scale(5);
opacity: 0;
}
}
优化性能的技巧
使用will-change属性提升动画性能:
.rain span {
will-change: transform, opacity;
}
减少雨滴数量在移动设备上:
const dropCount = window.innerWidth < 768 ? 50 : 100;
这些方法组合可以创建出逼真的下雨动画效果,通过调整参数如雨滴大小、速度、密度等可获得不同的视觉效果。






