HTML5 的普及速度有目共睹。在移動設備快速增長的當下,對 Flash 這類插件的依賴正在被剝離——Adobe 已宣布 Flash 不再支持移動平台,這本身就說明 HTML5 對移動端的重要性。桌面端的轉變也只是時間問題。
HTML 長久以來的短板是多媒體支持不足:既不能直接播放視頻,也無法在屏幕上自由作畫。HTML5 引入 <video> 與 <canvas> 後,開發者僅憑「純」HTML 加少量 JavaScript 就能處理多媒體任務,而動畫正是其中最基礎的一項能力。
本文只對比 <canvas> 與 CSS3 動畫兩條路線,DOM 或 SVG 方案不在討論範圍。需要提醒的是:canvas 在當前主流瀏覽器中已普遍支持,而 CSS3 動畫僅在新版 Firefox 與 Chrome 中可用,IE 下一版本才會跟進。因此文中示例建議在最新版 Chrome 下查看。
瀏覽器能夠優化聲明式的元素動畫(例如修改 CSS 樣式),而 canvas 上手繪的內容無法被同等優化。硬件加速依賴顯卡能力,目前瀏覽器並未開放直接訪問顯卡的途徑,每一個繪畫操作都要先經過瀏覽器自身的函數調用層。這意味著同樣的動畫,CSS3 往往能拿到更高的幀率。
<html>
<head>
<meta charset="UTF-8"/>
<title>Animation in HTML5 using the canvas element</title>
</head>
<body onload="init();">
<canvas id="canvas" width="1000" height="600">
Your browser does not support the <code><canvas></code>-element.
</canvas>
<div id="controls">
<button type="button" onclick="speed(-0.1);">Slower</button>
<button type="button" onclick="play(this);">Play</button>
<button type="button" onclick="speed(+0.1)">Faster</button>
</div>
</body>
</html>
先定義所需變量:
var dx=5, // 當前速率
rate=1, // 當前播放速度
ani, // 當前動畫循環
c, // 畫圖(Canvas Context)
w, // 汽車(隱藏的 Canvas Context)
grassHeight=130, // 背景高度
carAlpha=0, // 輪胎的旋轉角度
carX=-400, // x 軸方向汽車位置(會改變)
carY=300, // y 軸方向汽車位置(常量)
carWidth=400, // 汽車寬度
carHeight=130, // 汽車高度
tiresDelta=15, // 輪胎到車身底盤的距離
axisDelta=20, // 底盤軸與輪胎的距離
radius=60; // 輪胎半徑
用自執行匿名函數創建一塊離屏 canvas 專門畫車,避免每幀重複繪製靜態部分:
(function(){
var car=document.createElement('canvas'); // 創建元素
car.height=carHeight+axisDelta+radius; // 設置高度
car.width=carWidth; // 設置寬度
w=car.getContext('2d');
})();
點擊 Play 通過定時重複調用繪製函數模擬「幀播放」:
function play(s){ // 參數 s 是一個 button
if(ani){ // 已有動畫在跑
clearInterval(ani); // 清除定時器
ani=null;
s.innerHTML='Play'; // 按鈕改回「播放」
}else{
ani=setInterval(drawCanvas,40); // 25fps,40/1000
s.innerHTML='Pause';
}
}
加速與減速本質上是改變每幀位移量:
function speed(delta){
var newRate=Math.max(rate+delta,0.1);
dx=newRate/rate*dx;
rate=newRate;
}
初始化與主繪製流程:
function init(){
c=document.getElementById('canvas').getContext('2d');
drawCanvas();
}
function drawCanvas(){
c.clearRect(0,0,c.canvas.width, c.canvas.height); // 清屏
c.save(); // 保存狀態(push)
drawGrass(); // 畫背景
c.translate(carX,0); // 移動原點
drawCar(); // 在離屏畫布畫車
c.drawImage(w.canvas,0,carY); // 貼到主畫布
c.restore(); // 恢復狀態(pop)
carX+=dx; // 前進
carAlpha+=dx/radius; // 輪胎按比例轉動
if(carX>c.canvas.width){ // 越界重置
carX=-carWidth-10; // 也可改為 dx*=-1 反向
}
}
背景用線性漸變填充草地:
function drawGrass(){
// 前兩個參數為漸變起點,後兩個為終點
var grad=c.createLinearGradient(0,c.canvas.height-grassHeight,0,c.canvas.height);
grad.addColorStop(0,'#33CC00'); // 0 為起始色
grad.addColorStop(1,'#66FF22'); // 1 為終止色
c.fillStyle=grad;
c.lineWidth=0;
c.fillRect(0,c.canvas.height-grassHeight,c.canvas.width,grassHeight);
}
車身與輪胎:
function drawCar(){
w.clearRect(0,0,w.canvas.width,w.canvas.height); // 清空離屏畫布
w.strokeStyle='#FF6600'; // 邊框色
w.lineWidth=2; // 邊框寬度(像素)
w.fillStyle='#FF9900'; // 填充色
w.beginPath();
w.rect(0,0,carWidth,carHeight);
w.stroke();
w.fill();
w.closePath();
drawTire(tiresDelta+radius,carHeight+axisDelta); // 左輪
drawTire(carWidth-tiresDelta-radius,carHeight+axisDelta); // 右輪
}
function drawTire(x,y){
w.save();
w.translate(x,y);
w.rotate(carAlpha); // 依角度旋轉
w.strokeStyle='#3300FF';
w.lineWidth=1;
w.fillStyle='#0099FF';
w.beginPath();
w.arc(0,0,radius,0,2*Math.PI,false);
w.fill();
w.closePath();
w.beginPath();
w.moveTo(radius,0);
w.lineTo(-radius,0);
w.stroke();
w.closePath();
w.beginPath();
w.moveTo(0,radius);
w.lineTo(0,-radius);
w.stroke();
w.closePath();
w.restore();
}
第二種是純 CSS3 動畫,用 @keyframes 加 transform: translateX() 描述位移,浏覽器可交由合成器執行,性能最佳,但存在兼容問題;第三種是 CSS3 與 jQuery 結合,用 jQuery 切換 class 或觸發動畫事件,代碼量最少,適合快速落地。
由於 canvas 版本原理簡單且註釋完備,這裡不再逐行解讀。三種方案對比下來,若目標是流暢度優先且用戶環境可控,CSS3 是首選;需要像素級控制(例如輪胎隨位移旋轉)時,canvas 更合適。