星空闪烁效果

198 阅读1分钟

效果说明

本案例实现了一个星空闪烁的动画效果。每颗星星都有独立的闪烁频率和亮度变化,营造出梦幻的星空效果。

Snipaste_2024-12-18_22-38-17.png

核心实现

1. 星星的属性设计

每颗星星都有独特的属性,使其呈现不同的视觉效果:

reset() {
    this.x = Math.random() * canvas.width;    // 随机位置
    this.y = Math.random() * canvas.height;
    this.size = Math.random() * 2;            // 随机大小
    this.blinkSpeed = 0.01 + Math.random() * 0.02;  // 随机闪烁速度
    this.brightness = Math.random();          // 随机初始亮度
    this.maxBrightness = 0.5 + Math.random() * 0.5; // 随机最大亮度
}

2. 闪烁效果实现

通过控制亮度的增减来实现闪烁:

update() {
    if (this.increasing) {
        this.brightness += this.blinkSpeed;
        if (this.brightness >= this.maxBrightness) {
            this.increasing = false;
        }
    } else {
        this.brightness -= this.blinkSpeed;
        if (this.brightness <= 0) {
            this.increasing = true;
        }
    }
}

3. 星星的绘制

使用圆形和透明度创建星星效果:

draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
    ctx.fillStyle = `rgba(255, 255, 255, ${this.brightness})`;
    ctx.fill();
}

关键参数说明

  • size: 星星大小(0-2像素)
  • blinkSpeed: 闪烁速度(0.01-0.03)
  • brightness: 当前亮度(0-1)
  • maxBrightness: 最大亮度(0.5-1)

扩展思路

  1. 添加星星尾迹
  2. 实现流星效果
  3. 添加星座连线
  4. 实现鼠标交互效果
  5. 添加颜色变化

Demo