萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現鼠標跟隨氣泡特效:從經典代碼到現代重構

前言

鼠標跟隨氣泡特效是早期 Web 頁面常見的視覺裝飾,通過在滑鼠軌跡生成漸變氣泡營造動態氛圍。本文將解析經典實現邏輯,指出其侵入式 DOM 操作、全局變量污染、IE 專有 API 依賴等歷史包袱,並提供基於現代語法(ES6+、Canvas/RequestAnimationFrame)的重構方案,實現高性能、無依賴、易維護的氣泡特效。

經典實現邏輯解析

原代碼核心流程:

  1. 全局狀態管理:使用全局數組 object 存儲 60 個氣泡對象
  2. 滑鼠座標捕獲:document.onmousemove 更新全局 xm, ym
  3. 氣泡物件模型:CObj 構造函數初始化位置、速度、大小、振幅等參數
  4. 動畫循環:setInterval 每 16ms 驅動 ChteuMeulEu() 更新位置(正弦曲線水平擺動 + 垂直上升)
  5. 漸變背景生成:gradient() 動態插入 25 個 <span> 構建漸變色塊
  6. DOM 操作:大量使用 insertAdjacentHTML、document.write、element.style 直接操作樣式

歷史代碼的技術債

  • IE 專有 API:window.event、document.all、element.contains() 等不符合標準
  • 字符串定時器:setInterval("for(i in object)...", 16) 存在 eval 風險且難調試
  • 內存洩漏隱患:未清理的定時器、脫離文檔流的 DOM 節點
  • 性能瓶頸:頻繁讀寫 style.left/top 觸發強制重排
  • 全局命名空間污染:object, xm, ym, CObj, gradient, zyva 等全暴露

現代重構方案:Canvas + RequestAnimationFrame

採用 Canvas 繪圖替代 DOM 元素,配合 requestAnimationFrame 實現 60fps 流暢動畫,零 DOM 操作,極致性能。

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>現代鼠標跟隨氣泡特效</title>
    <style>
        * { margin: 0; padding: 0; }
        body { overflow: hidden; background: #000; height: 100vh; }
        canvas { display: block; }
    </style>
</head>
<body>
    <canvas id="bubbleCanvas"></canvas>
    <script>
        // 配置常量
        const CONFIG = {
            bubbleCount: 60,
            baseSpeed: 4,
            speedVariance: 6,
            sizeGrowth: 0.5,
            maxSize: 100,
            sineAmplitude: 0.5,
            sineFrequency: 0.1,
            trailColors: { r: 41, g: 93, b: 214 }, // 漸變基色
            gradientSteps: 25
        };

        // 狀態封裝
        const state = {
            mouse: { x: 0, y: 0 },
            bubbles: [],
            canvas: null,
            ctx: null,
            width: 0,
            height: 0,
            gradientCache: null
        };

        // 初始化
        function init() {
            state.canvas = document.getElementById('bubbleCanvas');
            state.ctx = state.canvas.getContext('2d');
            resize();
            window.addEventListener('resize', resize);
            window.addEventListener('mousemove', e => {
                state.mouse.x = e.clientX;
                state.mouse.y = e.clientY;
            });
            createBubbles();
            createGradientCache();
            animate();
        }

        // 響應式畫布
        function resize() {
            state.width = state.canvas.width = window.innerWidth;
            state.height = state.canvas.height = window.innerHeight;
            createGradientCache();
        }

        // 預渲染漸變緩存
        function createGradientCache() {
            const grad = state.ctx.createLinearGradient(0, 0, 0, state.height);
            for (let i = 0; i <= CONFIG.gradientSteps; i++) {
                const ratio = i / CONFIG.gradientSteps;
                const r = Math.round(CONFIG.trailColors.r * (1 - ratio));
                const g = Math.round(CONFIG.trailColors.g * (1 - ratio));
                const b = Math.round(CONFIG.trailColors.b * (1 - ratio));
                grad.addColorStop(ratio, `rgb(${r}, ${g}, ${b})`);
            }
            state.gradientCache = grad;
        }

        // 氣泡工廠
        function createBubbles() {
            state.bubbles = Array.from({ length: CONFIG.bubbleCount }, (_, i) => ({
                x: state.mouse.x,
                y: state.mouse.y + (i * state.height / CONFIG.bubbleCount),
                baseY: state.mouse.y + (i * state.height / CONFIG.bubbleCount),
                angle: Math.random() * Math.PI * 2,
                speed: CONFIG.baseSpeed + Math.random() * CONFIG.speedVariance,
                size: 0,
                maxSize: Math.random() * CONFIG.maxSize,
                phase: Math.random() * Math.PI * 2,
                hueOffset: Math.random() * 60
            }));
        }

        // 動畫主循環
        function animate() {
            const ctx = state.ctx;
            ctx.clearRect(0, 0, state.width, state.height);
            
            // 繪製漸變背景
            ctx.fillStyle = state.gradientCache;
            ctx.fillRect(0, 0, state.width, state.height);

            // 更新並繪製氣泡
            state.bubbles.forEach(bubble => {
                // 物理計算
                bubble.angle += CONFIG.sineFrequency;
                bubble.x = state.mouse.x + Math.sin(bubble.angle) * CONFIG.sineAmplitude * 100;
                bubble.y -= bubble.speed;
                bubble.size = Math.min(bubble.size + CONFIG.sizeGrowth, bubble.maxSize);

                // 超出頂部重置
                if (bubble.y < -bubble.maxSize) {
                    bubble.y = state.height + bubble.maxSize;
                    bubble.x = state.mouse.x;
                    bubble.size = 0;
                    bubble.phase = Math.random() * Math.PI * 2;
                }

                // 繪製氣泡 (簡化為圓形,可擴展為圖片/漸變)
                const alpha = 1 - bubble.y / state.height;
                ctx.beginPath();
                ctx.arc(bubble.x, bubble.y, bubble.size, 0, Math.PI * 2);
                ctx.fillStyle = `rgba(255, 255, 255, ${alpha * 0.6})`;
                ctx.fill();
            });

            requestAnimationFrame(animate);
        }

        // 啟動
        init();
    </script>
</body>
</html>

進階優化方向

  1. 粒子系統抽象:提取 Particle、Emitter、Renderer 類,支持多種特效複用
  2. WebGL 加速:大量粒子(>1000)時使用 WebGL 或 Three.js GPU 渲染
  3. 交互增強:點擊爆炸、滑鼠按下吸附、鍵盤控制參數
  4. 性能監控:集成 stats.js 監控 FPS、內存
  5. 配置面板:使用 dat.GUI 實時調參

總結

從表格佈局、document.write、全局變量的遠古時代,到 Canvas、requestAnimationFrame、模組化的現代工程,JavaScript 特效開發經歷了範式轉移。理解經典邏輯有助於閱讀遺留代碼,但生產環境請堅決採用現代技術棧:聲明式配置、狀態封裝、幂等渲染、性能優先。本文重構版僅 80 行核心代碼,即實現無依賴、高性能、響應式、可擴展的氣泡特效,歡迎在項目中直接使用或二次開發。

copyright © 萬盛學電腦網 all rights reserved