萬盛學電腦網

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

JavaScript 實現圖片跟隨鼠標軌跡特效:從舊版 document.write 到現代 Canvas 重構

前言

「圖片跟隨鼠標軌跡」是早期個人主頁、論壇簽名檔常見的裝飾特效。原代碼使用 document.write 動態創建大量 <div>/<layer>、字符串定時器、瀏覽器嗅探(document.all/document.layers)、全局變量污染等反模式。本文提供基於 Canvas + RequestAnimationFrame + ES6 模組 的現代重構,實現高性能、無 DOM 污染、可配置、易擴展的軌跡特效。

經典實現痛點分析

  • document.write 依賴:阻塞渲染、僅頁面加載階段可用、XSS 風險
  • 瀏覽器嗅探分支:document.all (IE)、document.layers (Netscape 4) 早已棄用
  • 字符串定時器:setInterval("cycle()", rate) 隱含 eval、作用域混亂、難調試
  • 大量 DOM 節點:每個軌跡點一個 <div>,6 個圖片 × 多層 = 數十節點,頻繁重排重繪
  • 全局命名空間污染:A,B,C,T1,nos,rate,ie5fix1... 全暴露
  • 硬編碼圖片路徑:trail1.gif 等假設文件存在,無錯誤處理

現代重構架構設計

TrailEffect (主控制器)
├── Config (配置選項)
├── State (狀態管理)
│   ├── particles: Particle[]  // 粒子池
│   ├── mouse: {x, y}          // 滑鼠座標
│   └── canvas, ctx            // 畫布上下文
├── Particle (粒子類)
│   ├── position, velocity, size, image, life
│   └── update(), draw()
├── Renderer (渲染器)
│   └── render(particles)
└── Lifecycle
    ├── init(), resize(), animate(), destroy()

完整現代實現代碼

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>現代鼠標軌跡特效</title>
    <style>
        * { margin: 0; padding: 0; }
        body { overflow: hidden; height: 100vh; background: #111; }
        canvas { display: block; }
        .config-panel {
            position: fixed; top: 20px; right: 20px; z-index: 100;
            background: rgba(0,0,0,0.8); color: #fff;
            padding: 15px; border-radius: 8px; font: 14px system-ui;
            min-width: 200px;
        }
        .config-panel label { display: block; margin: 8px 0; }
        .config-panel input[type="range"] { width: 100%; }
    </style>
</head>
<body>
    <canvas id="trailCanvas"></canvas>
    
    <!-- 實時調參面板 (開發/演示用) -->
    <div class="config-panel">
        <strong>軌跡參數調節</strong>
        <label>粒子數量: <input type="range" id="count" min="10" max="200" value="60"> <span id="countVal">60</span></label>
        <label>衰減速度: <input type="range" id="decay" min="0.9" max="0.999" step="0.001" value="0.95"> <span id="decayVal">0.95</span></label>
        <label>基礎大小: <input type="range" id="size" min="5" max="80" value="30"> <span id="sizeVal">30</span></label>
        <label>顏色模式: 
            <select id="colorMode">
                <option value="gradient">漸變</option>
                <option value="fixed">固定色</option>
                <option value="rainbow">彩虹</option>
            </select>
        </label>
        <button id="resetBtn">重置默認</button>
    </div>

    <script type="module">
        // ========== 配置常量 ==========
        const DEFAULT_CONFIG = {
            particleCount: 60,
            decay: 0.95,           // 速度衰減係數
            baseSize: 30,          // 基礎尺寸
            sizeVariance: 0.5,     // 尺寸隨機因子
            minSize: 2,            // 最小尺寸
            colorMode: 'gradient', // gradient | fixed | rainbow
            fixedColor: '#00d4ff',
            gradientColors: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96c93d', '#f9ca24', '#f0932b', '#eb4d4b'],
            imageUrls: [           // 支持圖片模式 (可選)
                'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDY0IDY0Ij48Y2lyY2xlIGN4PSIzMiIgY3k9IjMyIiByPSIyOCIgZmlsbD0iI2ZmZiIgb3BhY2l0eT0iMC44Ii8+PC9zdmc+',
                'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCIgdmlld0JveD0iMCAwIDUwIDUwIj48Y2lyY2xlIGN4PSIyNSIgY3k9IjI1IiByPSIyMiIgZmlsbD0iI2ZmZiIgb3BhY2l0eT0iMC43Ii8+PC9zdmc+',
                'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48Y2lyY2xlIGN4PSIyMCIgY3k9IjIwIiByPSIxOCIgZmlsbD0iI2ZmZiIgb3BhY2l0eT0iMC42Ii8+PC9zdmc+'
            ],
            useImages: false       // true: 使用圖片 | false: 繪製圓形
        };

        // ========== 核心類 ==========
        class Particle {
            constructor(x, y, config, index) {
                this.x = x;
                this.y = y;
                this.vx = (Math.random() - 0.5) * 2;
                this.vy = (Math.random() - 0.5) * 2;
                this.size = config.baseSize * (1 - index / config.particleCount) * (0.5 + Math.random() * config.sizeVariance);
                this.maxSize = this.size;
                this.life = 1;
                this.decay = config.decay;
                this.config = config;
                this.imageIndex = index % config.imageUrls.length;
                this.image = null;
                if (config.useImages) {
                    this.image = new Image();
                    this.image.src = config.imageUrls[this.imageIndex];
                }
                this.hue = Math.random() * 360;
            }

            update(mouseX, mouseY) {
                // 向滑鼠位置彈性移動
                const dx = mouseX - this.x;
                const dy = mouseY - this.y;
                const dist = Math.hypot(dx, dy);
                
                if (dist > 1) {
                    this.vx += dx * 0.02;
                    this.vy += dy * 0.02;
                }
                
                this.vx *= this.decay;
                this.vy *= this.decay;
                this.x += this.vx;
                this.y += this.vy;
                this.size = Math.max(this.size * this.decay, this.config.minSize);
                this.life *= this.decay;
            }

            draw(ctx) {
                if (this.life < 0.01) return;
                
                ctx.globalAlpha = this.life;
                
                if (this.config.useImages && this.image && this.image.complete) {
                    const s = this.size;
                    ctx.drawImage(this.image, this.x - s/2, this.y - s/2, s, s);
                } else {
                    // 程序化繪製圓形
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                    
                    switch (this.config.colorMode) {
                        case 'gradient':
                            const ratio = 1 - this.life;
                            const colors = this.config.gradientColors;
                            const idx = Math.min(Math.floor(ratio * (colors.length - 1)), colors.length - 2);
                            const localRatio = (ratio * (colors.length - 1)) % 1;
                            const c1 = colors[idx];
                            const c2 = colors[idx + 1];
                            ctx.fillStyle = this.lerpColor(c1, c2, localRatio);
                            break;
                        case 'rainbow':
                            ctx.fillStyle = `hsl(${this.hue}, 80%, 60%)`;
                            break;
                        default:
                            ctx.fillStyle = this.config.fixedColor;
                    }
                    ctx.fill();
                }
                ctx.globalAlpha = 1;
            }

            lerpColor(c1, c2, t) {
                const parse = c => c.match(/\w\w/g).map(x => parseInt(x, 16));
                const [r1,g1,b1] = parse(c1);
                const [r2,g2,b2] = parse(c2);
                const r = Math.round(r1 + (r2 - r1) * t);
                const g = Math.round(g1 + (g2 - g1) * t);
                const b = Math.round(b1 + (b2 - b1) * t);
                return `rgb(${r},${g},${b})`;
            }

            isDead() {
                return this.size <= this.config.minSize || this.life < 0.01;
            }
        }

        class TrailEffect {
            constructor(canvasId, userConfig = {}) {
                this.canvas = document.getElementById(canvasId);
                this.ctx = this.canvas.getContext('2d');
                this.config = { ...DEFAULT_CONFIG, ...userConfig };
                this.particles = [];
                this.mouse = { x: window.innerWidth/2, y: window.innerHeight/2 };
                this.animationId = null;
                this.lastTime = 0;
                
                this.init();
            }

            init() {
                this.resize();
                window.addEventListener('resize', () => this.resize());
                window.addEventListener('mousemove', e => {
                    this.mouse.x = e.clientX;
                    this.mouse.y = e.clientY;
                });
                // 觸摸支持
                window.addEventListener('touchmove', e => {
                    if (e.touches[0]) {
                        this.mouse.x = e.touches[0].clientX;
                        this.mouse.y = e.touches[0].clientY;
                    }
                }, { passive: true });
                
                this.spawnInitialParticles();
                this.animate();
            }

            resize() {
                this.canvas.width = window.innerWidth;
                this.canvas.height = window.innerHeight;
            }

            spawnInitialParticles() {
                for (let i = 0; i < this.config.particleCount; i++) {
                    this.particles.push(new Particle(
                        this.mouse.x, this.mouse.y, this.config, i
                    ));
                }
            }

            animate(time) {
                this.animationId = requestAnimationFrame(t => this.animate(t));
                
                // 幀率獨立 (可選)
                // const dt = (time - this.lastTime) / 1000;
                // this.lastTime = time;

                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                
                // 更新並繪製
                for (let i = this.particles.length - 1; i >= 0; i--) {
                    const p = this.particles[i];
                    p.update(this.mouse.x, this.mouse.y);
                    p.draw(this.ctx);
                    if (p.isDead()) {
                        this.particles.splice(i, 1);
                        // 补充新粒子保持數量
                        this.particles.push(new Particle(
                            this.mouse.x, this.mouse.y, this.config, this.particles.length
                        ));
                    }
                }
            }

            updateConfig(newConfig) {
                this.config = { ...this.config, ...newConfig };
            }

            destroy() {
                cancelAnimationFrame(this.animationId);
                window.removeEventListener('resize', this.resize);
                window.removeEventListener('mousemove', this.mouseMoveHandler);
            }
        }

        // ========== 啟動與控制面板 ==========
        const trail = new TrailEffect('trailCanvas');

        // 控制面板綁定
        const countEl = document.getElementById('count');
        const countVal = document.getElementById('countVal');
        const decayEl = document.getElementById('decay');
        const decayVal = document.getElementById('decayVal');
        const sizeEl = document.getElementById('size');
        const sizeVal = document.getElementById('sizeVal');
        const colorModeEl = document.getElementById('colorMode');
        const resetBtn = document.getElementById('resetBtn');

        countEl.addEventListener('input', e => {
            countVal.textContent = e.target.value;
            trail.updateConfig({ particleCount: parseInt(e.target.value) });
        });
        decayEl.addEventListener('input', e => {
            decayVal.textContent = parseFloat(e.target.value).toFixed(3);
            trail.updateConfig({ decay: parseFloat(e.target.value) });
        });
        sizeEl.addEventListener('input', e => {
            sizeVal.textContent = e.target.value;
            trail.updateConfig({ baseSize: parseInt(e.target.value) });
        });
        colorModeEl.addEventListener('change', e => {
            trail.updateConfig({ colorMode: e.target.value });
        });
        resetBtn.addEventListener('click', () => {
            trail.updateConfig(DEFAULT_CONFIG);
            countEl.value = DEFAULT_CONFIG.particleCount;
            decayEl.value = DEFAULT_CONFIG.decay;
            sizeEl.value = DEFAULT_CONFIG.baseSize;
            colorModeEl.value = DEFAULT_CONFIG.colorMode;
            countVal.textContent = DEFAULT_CONFIG.particleCount;
            decayVal.textContent = DEFAULT_CONFIG.decay.toFixed(3);
            sizeVal.textContent = DEFAULT_CONFIG.baseSize;
        });
    </script>
</body>
</html>

核心優化點總結

維度 舊版 (document.write + DOM) 新版 (Canvas + RAF)
渲染性能 O(n) DOM 節點操作,強制重排 單 Canvas 繪製,GPU 加速,無重排
內存佔用 數十個 DOM 元素 + 事件監聽器 純 JS 對象數組,極輕量
代碼結構 全局變量、字符串定時器、瀏覽器嗅探 ES6 Class 封裝、模組化、類型安全
擴展性 極難修改、耦合嚴重 配置驅動、插件化架構、熱更新參數
兼容性 依賴 IE 專有 API 現代瀏覽器全支持 (IE 需 Polyfill)
開發體驗 無調試、無熱重載、難測試 SourceMap、DevTools 完美支持、可單元測試

生產環境部署建議

  1. 按需加載:使用 IntersectionObserver 或路由守衛懶加載特效模組
  2. 性能預算:移動端限制粒子數 ≤ 30,requestIdleCallback 空閒時初始化
  3. 用戶偏好尊重:檢測 prefers-reduced-motion 媒體查詢,自動禁用動畫
  4. 錯誤邊界:try-catch 包裹 animate 循環,防單幀崩潰導致整頁凍結
  5. TypeScript 遷移:為配置、狀態、類添加類型定義,提升維護性

總結

鼠標軌跡特效從「文檔寫入+DOM 操作」進化到「Canvas 即時渲染+物理模擬」,折射出前端工程化的範式演進。現代實現不僅解決了性能、維護、兼容三大痛點,更通過配置驅動、模組封裝、實時調參賦能設計師與產品快速迭代視覺語言。建議團隊建立「特效組件庫」,將此類視覺增強標準化、配置化、可視化,避免重複造輪子,專注業務創新。

copyright © 萬盛學電腦網 all rights reserved