萬盛學電腦網

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

HTML5 三色彩帶跟隨滑鼠特效:Canvas 現代化重構與數學動畫原理

效果展示

三條彩色帶狀軌跡(金黃 #FFD000、綠 #00FF00、洋紅 #FF00FF)跟隨滑鼠游標,呈現正弦/餘弦波動軌跡,形成流動的彩帶效果。黑色背景下極具視覺衝擊力。

原始代碼架構分析

原版使用 document.write 動態產生 30 個 <div>(10 組 × 3 色),利用 setTimeout 輪詢更新每個元素的 style.left/top。核心數學公式:

YDummy[i] = ypos + Size * Math.sin((1*Math.sin(ThisStep/10)) + i*2) * Math.sin(ThisStep/4);
XDummy[i] = xpos + Size * Math.cos((1*Math.sin(ThisStep/10)) + i*2) * Math.sin(ThisStep/4);

其中 Size=120 控制擺動幅度,ThisStep 遞增驅動動畫,i*2 讓三色帶相位錯開。

現代化 Canvas 重構版(高效能、無 DOM 污染)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>三色彩帶 Canvas 版</title>
    <style>
        body { margin: 0; overflow: hidden; background: #000; height: 100vh; }
        canvas { display: block; }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        
        // 設定
        const COLORS = ['#FFD000', '#00FF00', '#FF00FF']; // 金、綠、洋紅
        const PARTICLES_PER_COLOR = 10;
        const SIZE = 120;          // 擺動半徑
        const STEP_INCREMENT = 0.02; // 動畫速度
        const PARTICLE_BASE_SIZE = 2; // 基礎粒子大小
        
        // 狀態
        let mouseX = window.innerWidth / 2;
        let mouseY = window.innerHeight / 2;
        let step = 0;
        let animationId;
        
        // 粒子陣列:每顆 { colorIndex, index, size }
        const particles = [];
        for (let c = 0; c < 3; c++) {
            for (let i = 0; i < PARTICLES_PER_COLOR; i++) {
                particles.push({
                    colorIndex: c,
                    index: i,
                    size: PARTICLE_BASE_SIZE + i * 1.5 // 遞增大小
                });
            }
        }
        
        // 滑鼠追蹤
        window.addEventListener('mousemove', e => {
            mouseX = e.clientX;
            mouseY = e.clientY;
        });
        
        // 觸控支援
        window.addEventListener('touchmove', e => {
            if (e.touches[0]) {
                mouseX = e.touches[0].clientX;
                mouseY = e.touches[0].clientY;
            }
        }, { passive: true });
        
        // 響應式尺寸
        function resize() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        }
        window.addEventListener('resize', resize);
        resize();
        
        // 核心動畫迴圈
        function animate() {
            // 清除畫布(半透明殘影效果可選)
            ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'; // 拖尾效果
            // ctx.clearRect(0, 0, canvas.width, canvas.height); // 無拖尾
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            step += STEP_INCREMENT;
            
            // 計算三色帶當前基準位置
            const bases = [];
            for (let c = 0; c < 3; c++) {
                const phase = (Math.sin(step / 10) + c * 2);
                const radius = Math.sin(step / 4) * SIZE;
                bases[c] = {
                    x: mouseX + Math.cos(phase) * radius,
                    y: mouseY + Math.sin(phase) * radius
                };
            }
            
            // 繪製每顆粒子(位置遞延產生拖尾)
            particles.forEach((p, i) => {
                const base = bases[p.colorIndex];
                // 位置插值:越後面的粒子越接近基準位置
                const t = (i % PARTICLES_PER_COLOR) / PARTICLES_PER_COLOR;
                const x = base.x; // 簡化:所有同色粒子同位置,靠大小區分
                const y = base.y;
                
                ctx.beginPath();
                ctx.arc(x, y, p.size, 0, Math.PI * 2);
                ctx.fillStyle = COLORS[p.colorIndex];
                ctx.fill();
            });
            
            animationId = requestAnimationFrame(animate);
        }
        
        animate();
        
        // 頁面隱藏時暫停
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) cancelAnimationFrame(animationId);
            else animate();
        });
    </script>
</body>
</html>

數學原理深度解析

雙重正弦波動

位置公式:pos = center + R * sin(ω₁t + φ) * sin(ω₂t)

  • sin(ω₁t + φ):控制角度方向(圓周運動)
  • sin(ω₂t):控制半徑大小(脈動效果)
  • 兩者相乘產生「花瓣狀」或「八字形」軌跡

相位錯開產生三色分離

φ = c * 2 讓三色帶在圓周上均勻分佈(約 120° 間隔),形成三條平行軌跡。

DOM 版本優化(若必須用 DOM 元素)

<style>
    .trail { position: fixed; pointer-events: none; border-radius: 50%; will-change: transform; }
</style>

<script>
// 建立粒子元素
const particles = [];
for (let c = 0; c < 3; c++) {
    for (let i = 0; i < 10; i++) {
        const el = document.createElement('div');
        el.className = 'trail';
        el.style.background = COLORS[c];
        el.style.width = el.style.height = (4 + i * 2) + 'px';
        document.body.appendChild(el);
        particles.push({ el, colorIndex: c, index: i });
    }
}

function animateDOM() {
    step += 0.02;
    const bases = calculateBases(); // 同 Canvas 版計算邏輯
    
    particles.forEach((p, i) => {
        const base = bases[p.colorIndex];
        const delay = p.index * 0.05; // 拖尾延遲
        const x = base.x + Math.sin(step * 2 + delay) * 10; // 微抖動
        const y = base.y + Math.cos(step * 2 + delay) * 10;
        p.el.style.transform = `translate(${x}px, ${y}px)`;
    });
    requestAnimationFrame(animateDOM);
}
animateDOM();
</script>

效能對比

指標原版 document.writeDOM 元素版Canvas 版
DOM 節點數30+301 (canvas)
重排/重繪極高 (style.left/top 觸發)高 (transform 較佳)無 (GPU 繪圖)
記憶體高中低
幀率穩定性差中優 (60fps)
拖尾效果需額外邏輯需額外邏輯單行代碼實現

創意變化應用

  • 粒子字體:將軌跡點連線形成文字
  • 聲音視覺化:結合 Web Audio API,頻率控制 SIZE/STEP
  • 互動遊戲:彩帶作為玩家軌跡、敵人躲避路徑
  • 載入動畫:頁面載入時展示品牌色彩帶
copyright © 萬盛學電腦網 all rights reserved