DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
HTML5 實作動畫的三種方式:Canvas、CSS3 與 jQuery 對比
編輯:HTML5詳解     

很多人一想到 HTML5 動畫就直覺聯想到 canvas,但其實那只是其中一條路。本文用同一個「行進中的小車」當範例,示範三種實作方式,讓你清楚看出各自的取捨:

  1. canvas 元素搭配 JavaScript 手繪每一格
  2. 純 CSS3 動畫(當時尚未被所有主流瀏覽器支援,例如 IE)
  3. CSS3 版面搭配 jQuery 驅動動畫

先說結論:懂得用 CSS3 動畫,往往比熟悉 <canvas> 更重要。因為瀏覽器能夠針對這類元素(特別是 CSS 樣式)做效能優化,而我們用 canvas 自己畫出來的東西無法被同樣地最佳化——原因在於瀏覽器主要依賴顯卡能力,但目前它並未開放讓我們直接操作顯卡,每一個繪圖指令都得先經過瀏覽器層轉一手。

註:受顯卡、錄製時的影格間隔與機器效能影響,實際播放可能會略有不順或有失真。

方式一:canvas + JavaScript

HTML

<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.
    Please think about updating your browser!
  </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,             // 目前的動畫迴圈 handle
    c,               // 主要畫布(Canvas Context)
    w,               // 汽車專用的隱藏畫布
    grassHeight=130, // 背景草皮高度
    carAlpha=0,      // 輪胎的旋轉角度
    carX=-400,       // 汽車 X 座標(會改變)
    carY=300,        // 汽車 Y 座標(固定)
    carWidth=400,    // 汽車寬度
    carHeight=130,   // 車身高度
    tiresDelta=15,   // 輪胎到車身底盤的距離
    axisDelta=20,    // 輪胎中心與底盤的間距
    radius=60;       // 輪胎半徑

建立一塊隱藏畫布來預先畫好車子

使用立即執行的匿名函式,把車身與輪胎先畫在記憶體中的 offscreen canvas 上,之後每一格只要 drawImage 貼上去即可,省下大量重繪成本。

(function(){
  var car = document.createElement('canvas'); // 建立元素
  car.height = carHeight + axisDelta + radius; // 設定高度
  car.width  = carWidth;                       // 設定寬度
  w = car.getContext('2d');
})();

播放與暫停:用計時器模擬影格

function play(s){            // 參數 s 是被點擊的按鈕
  if(ani){                   // 若已有動畫在跑
    clearInterval(ani);      // 清除它(停止動畫)
    ani = null;
    s.innerHTML = 'Play';    // 按鈕文字改回「播放」
  }else{
    ani = setInterval(drawCanvas, 40); // 40ms 一格,約 25fps
    s.innerHTML = 'Pause';             // 按鈕文字改為「暫停」
  }
}

加速與減速

本質上就是改變每格移動的距離 dx:

function speed(delta){
  var newRate = Math.max(rate + delta, 0.1); // 最低 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'); // 漸層起始色
  grad.addColorStop(1, '#66FF22'); // 漸層結束色
  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;           // 邊框寬度(px)
  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 動畫

接著你會看到,不寫一句 JavaScript,也能做出跟上面一模一樣的效果。

HTML

<html>
<head>
<meta charset="UTF-8" />
<title>Animations in Html5 using CSS3 animations</title>
</head>
<body>
  <div id="container">
    <div id="car">
      <div id="chassis"></div>
      <div id="backtire" class="tire">
        <div class="hr"></div>
        <div class="vr"></div>
      </div>
      <div id="fronttire" class="tire">
        <div class="hr"></div>
        <div class="vr"></div>
      </div>
    </div>
    <div id="grass"></div>
  </div>
</body>
</html>

定義 keyframes

每個動畫幾乎都要寫四個版本:原生、webkit(Chrome / Safari)、ms(向後相容 IE10)、moz(Firefox)。

/* 車身:從 -400px 移動到 1600px */
@keyframes carAnimation {
  0%   { left:-400px; }  /* 初始位置,0% 等同 from */
  100% { left:1600px; }  /* 最終位置,100% 等同 to */
}
@-webkit-keyframes carAnimation {
  0%   { left:-400px; }
  100% { left:1600px; }
}
@-moz-keyframes carAnimation {
  0%   { left:-400px; }
  100% { left:1600px; }
}
@-ms-keyframes carAnimation {
  0%   { left:-400px; }
  100% { left:1600px; }
}

/* 輪胎:旋轉五圈 */
@keyframes tyreAnimation {
  0%   { transform:rotate(0); }
  100% { transform:rotate(1800deg); }
}
@-webkit-keyframes tyreAnimation {
  0%   { -webkit-transform:rotate(0); }
  100% { -webkit-transform:rotate(1800deg); }
}
@-moz-keyframes tyreAnimation {
  0%   { -moz-transform:rotate(0); }
  100% { -moz-transform:rotate(1800deg); }
}
@-ms-keyframes tyreAnimation {
  0%   { -ms-transform:rotate(0); }
  100% { -ms-transform:rotate(1800deg); }
}

套用動畫於版面

body { padding:0; margin:0; }

#container {
  position:relative;
  width:100%;
  height:600px;
  overflow:hidden;   /* 這個很重要,車子才不會撐出畫面 */
}

#car {
  position:absolute; /* 汽車採絕對定位 */
  width:400px;
  height:210px;      /* 總高,含輪胎與底盤 */
  z-index:1;         /* 疊在背景之上 */
  top:300px;         /* 距頂端(Y 軸) */
  left:50px;         /* 距左側(X 軸) */

  -webkit-animation-name:carAnimation;
  -webkit-animation-duration:10s;
  -webkit-animation-iteration-count:infinite;
  -webkit-animation-timing-function:linear;
  -moz-animation-name:carAnimation;
  -moz-animation-duration:10s;
  -moz-animation-iteration-count:infinite;
  -moz-animation-timing-function:linear;
  -ms-animation-name:carAnimation;
  -ms-animation-duration:10s;
  -ms-animation-iteration-count:infinite;
  -ms-animation-timing-function:linear;
  animation-name:carAnimation;
  animation-duration:10s;
  animation-iteration-count:infinite;
  animation-timing-function:linear; /* 全程等速 */
}

/* 車身 */
#chassis {
  position:absolute;
  width:400px;
  height:130px;
  background:#FF9900;
  border:2px solid #FF6600;
}

/* 輪胎 */
.tire {
  z-index:1;
  position:absolute;
  bottom:0;
  border-radius:60px; /* 半徑 60 → 直徑 120 */
  height:120px;
  width:120px;
  background:#0099FF;
  border:1px solid #3300FF;
  -webkit-animation-name:tyreAnimation;
  -webkit-animation-duration:10s;
  -webkit-animation-iteration-count:infinite;
  -webkit-animation-timing-function:linear;
  -moz-animation-name:tyreAnimation;
  -moz-animation-duration:10s;
  -moz-animation-iteration-count:infinite;
  -moz-animation-timing-function:linear;
  -ms-animation-name:tyreAnimation;
  -ms-animation-duration:10s;
  -ms-animation-iteration-count:infinite;
  -ms-animation-timing-function:linear;
  animation-name:tyreAnimation;
  animation-duration:10s;
  animation-iteration-count:infinite;
  animation-timing-function:linear;
}

#fronttire { right:20px; }  /* 右輪距邊緣 20px */
#backtire  { left:20px;   }  /* 左輪距邊緣 20px */

#grass {
  position:absolute;
  width:100%;
  height:130px;
  bottom:0;
  background:linear-gradient(bottom, #33CC00, #66FF22);
  background:-webkit-linear-gradient(bottom, #33CC00, #66FF22);
  background:-moz-linear-gradient(bottom, #33CC00, #66FF22);
  background:-ms-linear-gradient(bottom, #33CC00, #66FF22);
}

.hr, .vr { position:absolute; background:#3300FF; }
.hr { height:1px; width:100%; left:0;   top:60px; } /* 輪胎水平線 */
.vr { width:1px;  height:100%; left:60px; top:0;   } /* 輪胎垂直線 */

方式三:jQuery + CSS3

這是一個效果與相容性都不錯的折衷方案,特別適合不支援 CSS3 動畫的舊版 IE。HTML 與 CSS 幾乎沿用上一節,只把 animation 相關宣告拿掉,改由 jQuery 驅動。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
  var rot = 0;

  // 找出目前瀏覽器實際吃哪個 transform 前綴
  var prefix = $('.tire').css('-o-transform') ? '-o-transform'
             : ($('.tire').css('-ms-transform') ? '-ms-transform'
             : ($('.tire').css('-moz-transform') ? '-moz-transform'
             : ($('.tire').css('-webkit-transform') ? '-webkit-transform'
             : 'transform')));

  var origin    = { left:-400 };  // 起點
  var animation = { left:1600 };  // 終點,交由 jQuery 執行

  var rotate = function(){        // 每一步旋轉輪胎
    rot += 2;
    $('.tire').css(prefix, 'rotate(' + rot + 'deg)');
  };

  var options = {
    easing:'linear',              // 等速
    duration:10000,               // 持續 10 秒
    complete:function(){
      $('#car').css(origin).animate(animation, options); // 完成後再啟動,形成無限迴圈
    },
    step:rotate                   // 每個影格呼叫
  };

  options.complete();
});
</script>

流程很直觀:先判斷該用哪個 transform 前綴,接著定義起點與終點,再寫一個負責累加旋轉角度的函式並掛在 step 上,最後用 complete 回呼自我遞迴呼叫,就得到一個無限循環的動畫。

該選哪一種?

  • canvas + JS:控制力最強,適合粒子、遊戲、需要動態運算的場景;但所有繪圖細節都得自己實作,也難以享受瀏覽器的渲染優化。
  • 純 CSS3:程式碼最乾淨、效能最好,適合位置、旋轉、透明度這類可以宣告式表達的動畫;缺點是複雜互動與動態計算不方便。
  • CSS3 + jQuery:兼顧開發速度與相容性,適合需要中途改變參數、或要支援舊瀏覽器的專案。

一個簡單的小車範例,就把 HTML5 時代常見的三種動畫路徑都跑過一次。理解彼此的邊界之後,真正該練的功課是判斷——依需求挑最省事又最流暢的那一種。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved