萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

HTML5 Canvas 實現跟隨滑鼠的雪花飄落特效

前言

經典的「滑鼠跟隨雪花」特效常用於節日專題頁。現代寫法採用 <canvas> + requestAnimationFrame,效能遠優於早期 DOM 大量建立 <img> 的做法。本文提供完整、可調參數、支援高 DPI 的實作。

完整單檔案範例

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>Canvas 雪花跟隨滑鼠</title>
  <style>
    html, body { margin: 0; height: 100%; overflow: hidden; background: #000; }
    canvas { display: block; }
  </style>
</head>
<body>
  <canvas id="snow"></canvas>
  <script>
    const canvas = document.getElementById('snow');
    const ctx = canvas.getContext('2d');

    // 高 DPI 支援
    function resize() {
      const dpr = window.devicePixelRatio || 1;
      canvas.width = innerWidth * dpr;
      canvas.height = innerHeight * dpr;
      ctx.scale(dpr, dpr);
      canvas.style.width = innerWidth + 'px';
      canvas.style.height = innerHeight + 'px';
    }
    window.addEventListener('resize', resize);
    resize();

    // 參數配置
    const CONFIG = {
      count: 120,           // 雪花數量
      minSize: 2, maxSize: 6,
      minSpeed: 0.5, maxSpeed: 2,
      wind: 0.2,            // 水平飄移
      mouseInfluence: 0.05, // 滑鼠吸引力
      color: 'rgba(255,255,255,0.8)'
    };

    // 滑鼠位置
    const mouse = { x: innerWidth/2, y: innerHeight/2 };
    window.addEventListener('mousemove', e => { mouse.x = e.clientX; mouse.y = e.clientY; });

    // 雪花類別
    class Flake {
      constructor() { this.reset(true); }
      reset(init = false) {
        this.x = Math.random() * innerWidth;
        this.y = init ? Math.random() * innerHeight : -CONFIG.maxSize;
        this.size = Math.random() * (CONFIG.maxSize - CONFIG.minSize) + CONFIG.minSize;
        this.speedY = Math.random() * (CONFIG.maxSpeed - CONFIG.minSpeed) + CONFIG.minSpeed;
        this.speedX = (Math.random() - 0.5) * CONFIG.wind;
        this.opacity = Math.random() * 0.5 + 0.3;
      }
      update() {
        // 滑鼠吸引
        const dx = mouse.x - this.x;
        const dy = mouse.y - this.y;
        const dist = Math.hypot(dx, dy);
        if (dist < 200) {
          this.speedX += dx * CONFIG.mouseInfluence;
          this.speedY += dy * CONFIG.mouseInfluence;
        }
        this.x += this.speedX;
        this.y += this.speedY;
        // 邊界回收
        if (this.y > innerHeight + this.size || this.x < -this.size || this.x > innerWidth + this.size) {
          this.reset();
        }
      }
      draw() {
        ctx.globalAlpha = this.opacity;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fillStyle = CONFIG.color;
        ctx.fill();
      }
    }

    // 初始化雪花陣列
    const flakes = Array.from({ length: CONFIG.count }, () => new Flake());

    // 動畫迴圈
    function animate() {
      ctx.clearRect(0, 0, innerWidth, innerHeight);
      flakes.forEach(f => { f.update(); f.draw(); });
      requestAnimationFrame(animate);
    }
    animate();
  </script>
</body>
</html>

核心技術點解析

技術說明
requestAnimationFrame瀏覽器繪製前回調,同步螢幕重繪率 (60/120fps),避免掉幀。
devicePixelRatio解決高解析度螢幕 (Retina/2K/4K) 畫面模糊,Canvas 內部解析度放大再縮放。
物件池模式雪花陣列固定長度,超出邊界時 reset() 重用,避免 GC 抖動。
向量數學使用 Math.hypot 計算距離,依距離施加吸引力向量。
globalAlpha統一設定透明度,比逐顆粒 rgba 更高效。

進階擴充想法

  • 多層景深:建立 3 組雪花陣列,size/speed/opacity 遞減,繪製順序背→前,製造 3D 感。
  • 風向變化:用 Perlin Noise 產生平滑隨機風向,隨時間演變。
  • 互動爆發:點擊產生雪花爆炸粒子系統。
  • 效能監控:stats.js 或 performance.now() 監控幀時間,超過 16ms 自動降級減少雪花數。

無障礙與效能提醒

  • 提供 prefers-reduced-motion 媒體查詢關閉動畫:@media (prefers-reduced-motion: reduce) { canvas { display: none; } }。
  • 長時間運行頁面請加入「暫停/關閉特效」按鈕,避免持續佔用 GPU/電量。
  • 移動裝置無滑鼠事件,改用 touchmove 或關閉滑鼠吸引邏輯。

Canvas 粒子系統是前端視覺特效基礎,掌握此模式可延伸至煙火、氣泡、星空、數據可視化等多種場景。

copyright © 萬盛學電腦網 all rights reserved