用canvas实现动态雪花飘落的核心是管理每片雪的状态(位置、速度、大小、透明度等),通过requestanimationframe逐帧更新与重绘;需初始化自适应canvas、定义snowflake类并随机生成数百片雪,超出边界时重置。

用 Canvas 实现动态雪花飘落,核心是模拟雪花的随机生成、下落运动、碰撞边界与重置逻辑,配合 requestAnimationFrame 实现平滑动画。关键不在“画雪花”,而在“管雪花”——每片雪要独立维护位置、速度、大小、透明度等状态,并在每一帧中更新和重绘。
1. 初始化 Canvas 与基础上下文
先获取 DOM 中的 <canvas></canvas> 元素,设置宽高(建议设为窗口尺寸),并获取 2D 渲染上下文:
const canvas = document.getElementById('snowCanvas');
const ctx = canvas.getContext('2d');
<p>// 自适应窗口大小
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);</p>注意:不要用 CSS 缩放 canvas,否则会模糊;务必通过 canvas.width/height 属性设置真实像素尺寸。
2. 定义雪花类与随机初始化
每片雪花是一个对象,含 x、y(坐标)、speed(下落速度)、size(半径)、opacity(透明度)、drift(左右偏移量)等属性:
class Snowflake {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * -100; // 从屏幕上方外开始
this.size = Math.random() * 3 + 1; // 1–4px
this.speed = Math.random() * 2 + 0.5; // 0.5–2.5 px/frame
this.opacity = Math.random() * 0.5 + 0.3; // 0.3–0.8
this.drift = (Math.random() - 0.5) * 0.5; // 左右轻微摆动
}
update() {
this.y += this.speed;
this.x += this.drift;
// 超出底部则重置
if (this.y > canvas.height) this.reset();
// 可选:碰到左右边界也重置或反弹
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.opacity})`;
ctx.fill();
}
}
创建雪花数组(如 200–500 片),避免过多影响性能:
const snowflakes = []; const snowCount = 300; for (let i = 0; i
3. 动画循环与渲染逻辑
使用 requestAnimationFrame 替代 setInterval,保证 60fps 流畅性。每帧需清空画布(用 clearRect),再逐个更新+绘制雪花:
function animate() {
// 清空画布(只清背景,不重绘整个页面)
ctx.clearRect(0, 0, canvas.width, canvas.height);
<p>// 更新并绘制每片雪花
snowflakes.forEach(flake => {
flake.update();
flake.draw();
});</p><p>requestAnimationFrame(animate);
}
animate();</p>小技巧:若想加“风”的效果,可在 update() 中引入时间偏移或全局风速变量;若想更真实,可让大雪花下落更快、小雪花飘得更慢且晃动更明显。
4. 增强体验的实用优化
-
性能控制:当页面失焦(如切到其他标签页)时暂停动画,用
document.hidden监听可见性变化 -
交互响应:鼠标移动时改变风向,让雪花轻微倾斜(修改
drift的基准值) - 视觉层次:分三层雪花(近/中/远),近层大而快、远层小而慢+低透明度,用不同数组管理
- 防抖重绘:窗口缩放后立即重置所有雪花位置,避免大片雪花卡在顶部或消失
不复杂但容易忽略:Canvas 是位图,没有图层概念,所以“雪花飘过文字”需要确保文字在 canvas 上层(用 CSS z-index)或直接用 canvas 绘制文字。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











