js实现飘雪
实现飘雪效果的方法
在JavaScript中实现飘雪效果可以通过Canvas或CSS动画来完成。以下是两种常见的方法:
使用Canvas实现飘雪
Canvas适合需要大量粒子效果的场景,性能较好。
const canvas = document.getElementById('snowCanvas');
const ctx = canvas.getContext('2d');
// 设置canvas为全屏
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 雪花数组
const snowflakes = [];
// 创建雪花
class Snowflake {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = Math.random() * 4 + 1;
this.speed = Math.random() * 3 + 1;
this.opacity = Math.random();
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.opacity})`;
ctx.fill();
}
update() {
this.y += this.speed;
if (this.y > canvas.height) {
this.y = 0;
this.x = Math.random() * canvas.width;
}
this.draw();
}
}
// 初始化雪花
for (let i = 0; i < 100; i++) {
snowflakes.push(new Snowflake());
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snowflakes.forEach(snowflake => snowflake.update());
requestAnimationFrame(animate);
}
animate();
// 窗口大小改变时重置canvas
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
HTML中需要添加一个canvas元素:
<canvas id="snowCanvas"></canvas>
使用CSS实现飘雪
CSS方法更简单,适合少量雪花效果。
<div class="snow-container"></div>
.snow-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 1000;
}
.snow {
position: absolute;
background-color: white;
border-radius: 50%;
pointer-events: none;
animation: fall linear infinite;
}
@keyframes fall {
to {
transform: translateY(100vh);
}
}
function createSnow() {
const snow = document.createElement('div');
snow.className = 'snow';
// 随机大小
const size = Math.random() * 10 + 5;
snow.style.width = `${size}px`;
snow.style.height = `${size}px`;
// 随机位置
snow.style.left = `${Math.random() * window.innerWidth}px`;
snow.style.top = '-10px';
// 随机透明度
snow.style.opacity = Math.random();
// 随机动画时长
const duration = Math.random() * 5 + 5;
snow.style.animationDuration = `${duration}s`;
document.querySelector('.snow-container').appendChild(snow);
// 动画结束后移除
setTimeout(() => {
snow.remove();
}, duration * 1000);
}
// 每隔一段时间创建雪花
setInterval(createSnow, 100);
性能优化建议
对于大量雪花效果,Canvas通常性能更好。可以调整以下参数优化性能:

- 减少雪花数量
- 降低动画帧率
- 使用requestAnimationFrame代替setInterval
- 避免在动画循环中频繁创建对象
两种方法都可以根据需求进行调整,Canvas更适合复杂的粒子效果,CSS方法则更简单易用。






