鼠標跟隨氣泡特效是早期 Web 頁面常見的視覺裝飾,通過在滑鼠軌跡生成漸變氣泡營造動態氛圍。本文將解析經典實現邏輯,指出其侵入式 DOM 操作、全局變量污染、IE 專有 API 依賴等歷史包袱,並提供基於現代語法(ES6+、Canvas/RequestAnimationFrame)的重構方案,實現高性能、無依賴、易維護的氣泡特效。
原代碼核心流程:
object 存儲 60 個氣泡對象document.onmousemove 更新全局 xm, ymCObj 構造函數初始化位置、速度、大小、振幅等參數setInterval 每 16ms 驅動 ChteuMeulEu() 更新位置(正弦曲線水平擺動 + 垂直上升)gradient() 動態插入 25 個 <span> 構建漸變色塊insertAdjacentHTML、document.write、element.style 直接操作樣式window.event、document.all、element.contains() 等不符合標準setInterval("for(i in object)...", 16) 存在 eval 風險且難調試style.left/top 觸發強制重排object, xm, ym, CObj, gradient, zyva 等全暴露採用 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>
Particle、Emitter、Renderer 類,支持多種特效複用WebGL 或 Three.js GPU 渲染stats.js 監控 FPS、內存dat.GUI 實時調參從表格佈局、document.write、全局變量的遠古時代,到 Canvas、requestAnimationFrame、模組化的現代工程,JavaScript 特效開發經歷了範式轉移。理解經典邏輯有助於閱讀遺留代碼,但生產環境請堅決採用現代技術棧:聲明式配置、狀態封裝、幂等渲染、性能優先。本文重構版僅 80 行核心代碼,即實現無依賴、高性能、響應式、可擴展的氣泡特效,歡迎在項目中直接使用或二次開發。