萬盛學電腦網

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

JavaScript 實作跟隨滑鼠閃爍旋轉色塊特效

效果描述

頁面上出現多個彩色方塊,隨著滑鼠移動平滑跟隨,並持續閃爍(發光)、旋轉、縮放,形成動態視覺焦點。原始碼為 IE 專屬寫法(document.all、event.x/y、filter: glow),現代瀏覽器需重寫。

現代化重構(Canvas + requestAnimationFrame)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  body { margin: 0; overflow: hidden; background: #111; }
  canvas { display: block; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<script>
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
const colours = ['#ff0000','#00ff00','#3366ff','#ff00ff','#ffa500','#ffffff','#fff000'];
const count = colours.length;
const particles = colours.map((c, i) => ({
    color: c, angle: (i / count) * Math.PI * 2, radius: 150
}));

let mouseX = innerWidth / 2, mouseY = innerHeight / 2;
let glowPhase = 0, growing = true;

function resize() {
    canvas.width = innerWidth;
    canvas.height = innerHeight;
}
window.addEventListener('resize', resize);
resize();

window.addEventListener('mousemove', e => {
    mouseX = e.clientX;
    mouseY = e.clientY;
});

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 更新發光相位
    glowPhase += growing ? 0.05 : -0.05;
    if (glowPhase > 1) { glowPhase = 1; growing = false; }
    if (glowPhase < 0) { glowPhase = 0; growing = true; }

    particles.forEach((p, i) => {
        // 旋轉軌跡
        p.angle += 0.02;
        const x = mouseX + Math.cos(p.angle) * p.radius;
        const y = mouseY + Math.sin(p.angle) * p.radius;

        // 繪製發光方塊
        const size = 40;
        ctx.save();
        ctx.translate(x, y);
        ctx.rotate(p.angle * 2);
        ctx.shadowColor = p.color;
        ctx.shadowBlur = 20 * glowPhase;
        ctx.fillStyle = p.color;
        ctx.fillRect(-size/2, -size/2, size, size);
        ctx.restore();
    });

    requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>

關鍵技術點

  • Canvas 2D:高效繪製大量圖形,避免 DOM 節點過多導致回流重繪。
  • requestAnimationFrame:與螢幕重繪同步,動畫流暢且省電。
  • 滑鼠座標平滑跟隨:可加入緩動(mouseX += (targetX - mouseX) * 0.1)讓跟隨更有機感。
  • 發光效果:ctx.shadowBlur + 動態 shadowColor 替代舊版 filter: glow。

原始碼歷史註記

原文使用 document.write 動態產生 <div>、setTimeout 遞迴驅動、IE 專屬 event.x/y 及 filter: glow,僅供歷史參考,不可用於現代專案。

copyright © 萬盛學電腦網 all rights reserved