飘动雪花背景

392 阅读1分钟

效果说明

本案例实现了一个飘动的雪花背景效果。通过为每个雪花添加左右摆动的运动,模拟真实的雪花飘落效果。每个雪花都有独立的大小、速度和摆动幅度,营造出自然的视觉效果。

Snipaste_2024-12-16_22-39-14.png

核心实现

1. 雪花对象设计

每个雪花都包含位置、大小、速度和摆动相关的属性:

class Snowflake {
    constructor() {
        this.x = Math.random() * canvas.width;  // 随机水平位置
        this.y = -10;                          // 从顶部开始
        this.size = 2 + Math.random() * 4;     // 随机大小
        this.speed = 1 + Math.random() * 2;    // 随机速度
        this.swing = Math.random() * 3;        // 摆动幅度
        this.swingCount = Math.random() * Math.PI * 2; // 摆动角度
    }
}

2. 雪花飘动原理

使用正弦函数实现左右摆动,同时保持匀速下落:

update() {
    // 通过改变角度实现周期性摆动
    this.swingCount += 0.02;
    // 水平位置 = 当前位置 + sin(角度) * 摆动幅度
    this.x += Math.sin(this.swingCount) * this.swing;
    // 垂直位置 = 当前位置 + 下落速度
    this.y += this.speed;
}

摆动效果的关键是使用 Math.sin() 函数:

  • swingCount 不断增加,使得正弦值在-1到1之间循环变化
  • swing 控制摆动的幅度
  • 最终的水平偏移量为 sin(角度) * 摆动幅度

3. 轨迹效果实现

通过绘制半透明背景层,形成雪花飘落的轨迹:

ctx.fillStyle = 'rgba(17, 34, 51, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);

扩展思路

  1. 添加风向影响效果
  2. 实现雪花旋转动画
  3. 添加鼠标交互效果
  4. 实现雪花积累效果

Demo