經典的「滑鼠跟隨雪花」特效常用於節日專題頁。現代寫法採用 <canvas> + requestAnimationFrame,效能遠優於早期 DOM 大量建立 <img> 的做法。本文提供完整、可調參數、支援高 DPI 的實作。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>Canvas 雪花跟隨滑鼠</title>
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #000; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="snow"></canvas>
<script>
const canvas = document.getElementById('snow');
const ctx = canvas.getContext('2d');
// 高 DPI 支援
function resize() {
const dpr = window.devicePixelRatio || 1;
canvas.width = innerWidth * dpr;
canvas.height = innerHeight * dpr;
ctx.scale(dpr, dpr);
canvas.style.width = innerWidth + 'px';
canvas.style.height = innerHeight + 'px';
}
window.addEventListener('resize', resize);
resize();
// 參數配置
const CONFIG = {
count: 120, // 雪花數量
minSize: 2, maxSize: 6,
minSpeed: 0.5, maxSpeed: 2,
wind: 0.2, // 水平飄移
mouseInfluence: 0.05, // 滑鼠吸引力
color: 'rgba(255,255,255,0.8)'
};
// 滑鼠位置
const mouse = { x: innerWidth/2, y: innerHeight/2 };
window.addEventListener('mousemove', e => { mouse.x = e.clientX; mouse.y = e.clientY; });
// 雪花類別
class Flake {
constructor() { this.reset(true); }
reset(init = false) {
this.x = Math.random() * innerWidth;
this.y = init ? Math.random() * innerHeight : -CONFIG.maxSize;
this.size = Math.random() * (CONFIG.maxSize - CONFIG.minSize) + CONFIG.minSize;
this.speedY = Math.random() * (CONFIG.maxSpeed - CONFIG.minSpeed) + CONFIG.minSpeed;
this.speedX = (Math.random() - 0.5) * CONFIG.wind;
this.opacity = Math.random() * 0.5 + 0.3;
}
update() {
// 滑鼠吸引
const dx = mouse.x - this.x;
const dy = mouse.y - this.y;
const dist = Math.hypot(dx, dy);
if (dist < 200) {
this.speedX += dx * CONFIG.mouseInfluence;
this.speedY += dy * CONFIG.mouseInfluence;
}
this.x += this.speedX;
this.y += this.speedY;
// 邊界回收
if (this.y > innerHeight + this.size || this.x < -this.size || this.x > innerWidth + this.size) {
this.reset();
}
}
draw() {
ctx.globalAlpha = this.opacity;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = CONFIG.color;
ctx.fill();
}
}
// 初始化雪花陣列
const flakes = Array.from({ length: CONFIG.count }, () => new Flake());
// 動畫迴圈
function animate() {
ctx.clearRect(0, 0, innerWidth, innerHeight);
flakes.forEach(f => { f.update(); f.draw(); });
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
| 技術 | 說明 |
|---|---|
| requestAnimationFrame | 瀏覽器繪製前回調,同步螢幕重繪率 (60/120fps),避免掉幀。 |
| devicePixelRatio | 解決高解析度螢幕 (Retina/2K/4K) 畫面模糊,Canvas 內部解析度放大再縮放。 |
| 物件池模式 | 雪花陣列固定長度,超出邊界時 reset() 重用,避免 GC 抖動。 |
| 向量數學 | 使用 Math.hypot 計算距離,依距離施加吸引力向量。 |
| globalAlpha | 統一設定透明度,比逐顆粒 rgba 更高效。 |
stats.js 或 performance.now() 監控幀時間,超過 16ms 自動降級減少雪花數。prefers-reduced-motion 媒體查詢關閉動畫:@media (prefers-reduced-motion: reduce) { canvas { display: none; } }。touchmove 或關閉滑鼠吸引邏輯。Canvas 粒子系統是前端視覺特效基礎,掌握此模式可延伸至煙火、氣泡、星空、數據可視化等多種場景。