以《植物大戰殭屍》網頁版為例,分享 HTML5 遊戲開發中動畫控制、解析度適配、平板手機識別的核心技巧與踩坑經驗。
GIF/APNG 無法程式控制播放狀態。採用 **CSS Animation + Sprite Sheet(雪碧圖)**,配合 JS 事件監聽實現精確控制。
| 事件 | 觸發時機 |
|---|---|
animationstart | 動畫開始(含 delay 後) |
animationend | 動畫結束 |
animationiteration | 每次循環結束 |
transitionstart | 過渡開始 |
transitionend | 過渡結束 |
各瀏覽器需加前綴(`webkitAnimationEnd` 等),建議封裝統一監聽函式。
animationend 事件鏈式觸發下一個動畫若需在動畫 30% 處觸發回呼:
let animStartTime, animDuration = 10000; // 10s
function startAnim() {
animStartTime = performance.now();
el.classList.add('running');
tick();
}
function tick() {
if (!el.classList.contains('running')) return;
const progress = (performance.now() - animStartTime) / animDuration;
if (progress >= 0.3 && !triggered) { callback(); triggered = true; }
if (progress < 1) requestAnimationFrame(tick);
}
// 暫停/繼續時同步更新 animStartTime
此法有微小誤差,精度要求高請改用 Web Animations API 或 Canvas 幀級控制。
Viewport 與 Media Query 在 iOS(裝置像素)與 Android(CSS 像素)表現不一,且遊戲大量使用絕對定位,彈性佈局計算量大且不精準。
const ua = navigator.userAgent;
const isAndroid = /Android/.test(ua);
const isIOS = /iPhone|iPad|iPod/.test(ua);
if (isAndroid) {
// Android:對最外層容器縮放
document.documentElement.style.transform = `scale(${scale})`;
document.documentElement.style.transformOrigin = '0 0';
} else if (isIOS) {
// iOS:使用 viewport 縮放
const meta = document.querySelector('meta[name=viewport]');
meta.content = `width=device-width, initial-scale=${scale}, maximum-scale=${scale}, user-scalable=no`;
}
配合 `rem`/`vm` 單位或固定畫布尺寸 + `transform: scale()`,確保像素級對齊。
CSS 解析度不可靠(老平板解析度低、新手機解析度高)。核心邏輯:**計算物理螢幕尺寸(英寸)**。
function getDeviceFormFactor() {
const dpi = window.screen.deviceXDPI || window.screen.logicalXDPI || 96;
const wInch = screen.width / dpi;
const hInch = screen.height / dpi;
const diagonal = Math.sqrt(wInch*wInch + hInch*hInch);
return diagonal > 6.5 ? 'tablet' : 'phone'; // 經驗閾值
}
再根據裝置類型載入對應解析度素材(@2x/@3x),避免平板顯示模糊、手機載入過大資源。
掌握這三大核心,能讓 HTML5 遊戲在碎片化行動裝置上跑出接近 Native 的流暢體驗。