Google 首頁的 Doodle 動畫常讓人驚嘆,其核心技術之一即 CSS Sprite(CSS 精靈圖)。本文通過實戰拆解,示範如何用一張精靈圖 + JavaScript 定時切換 background-position,輕鬆實現幀動畫效果。
<div> 疊放在同一位置,僅 background-position 不同setInterval 循環切換各 <div> 的顯示/隱藏,或直接操作單個元素的 background-position

通過開發者工具發現,Google 會動態生成類似以下結構:
<div id="hplogo0" style="left:307px;top:48px;width:88px;height:89px;background:url(sprite.png) 0 0 no-repeat;"></div>
<div id="hplogo1" style="left:307px;top:48px;width:89px;height:89px;background:url(sprite.png) -88px 0 no-repeat;"></div>
<div id="hplogo2" style="left:307px;top:48px;width:91px;height:89px;background:url(sprite.png) -177px 0 no-repeat;"></div>
... 共 12 幀 ...
每幀寬高、定位略有差異,對應精靈圖中不同位置。
const frames = [
{x: 0, w: 88, h: 89, l: 307, t: 48},
{x: -88, w: 89, h: 89, l: 307, t: 48},
{x: -177,w: 91, h: 89, l: 307, t: 48},
{x: -268,w: 93, h: 89, l: 305, t: 49},
{x: -361,w: 93, h: 88, l: 305, t: 50},
{x: -454,w: 93, h: 88, l: 305, t: 50},
{x: -547,w: 92, h: 86, l: 306, t: 52},
{x: -639,w: 93, h: 84, l: 305, t: 53},
{x: -732,w: 94, h: 83, l: 305, t: 54},
{x: -826,w: 93, h: 83, l: 306, t: 54},
{x: -919,w: 92, h: 83, l: 307, t: 54}
];
const logo = document.getElementById('logo');
let i = 0;
setInterval(() => {
const f = frames[i];
logo.style.width = f.w + 'px';
logo.style.height = f.h + 'px';
logo.style.left = f.l + 'px';
logo.style.top = f.t + 'px';
logo.style.backgroundPosition = f.x + 'px 0';
i = (i + 1) % frames.length;
}, 100); // 100ms/幀 ≈ 10fps
若精靈圖幀尺寸固定、排列整齊,可直接用 CSS Animation:
@keyframes doodle {
from { background-position: 0 0; }
to { background-position: -1104px 0; } /* 12幀 × 92px */
}
#logo {
width: 92px; height: 89px;
background: url(sprite.png) no-repeat;
animation: doodle 1.2s steps(12) infinite;
}
background-position 負值向左/向上偏移steps() 純 CSS 方案,性能更優掌握 Sprite 動畫,不僅能還原 Google Doodle,更能應用於遊戲角色動作、載入圖標、UI 微動效等場景。