HTML5實現動畫三種方式


HTML5實現動畫三種方式

文章目錄

編者注:作者以一個運動的小車爲例子,講述了三種實現HTML5動畫的方式,思路清晰,動畫不僅僅是canvas,還有css3和javascript.通過合理的選擇,來實現最優的實現。

原文來自http://caibaojian.com/3-html5-animations.html

PS:由於顯卡、錄製的幀間隔,以及可能你電腦處理器的原因,播放過程可能有些不太流暢或者失真!

分三種方式實現:

(1)   canvas元素結合JS

(2)   純粹的CSS3動畫(暫不被所有主流瀏覽器支持,比如IE)

(3)   CSS3結合Jquery實現

知道如何使用CSS3動畫比知道如何使用<canvas>元素更重要:因爲瀏覽器能夠優化那些元素的性能(通常是他們的樣式,比如CSS),而我們使用canvas自定義畫出來的效果卻不能被優化。原因又在於,瀏覽器使用的硬件主要取決於顯卡的能力。目前,瀏覽器沒有給予我們直接訪問顯卡的權力,比如,每一個繪畫操作都不得不在瀏覽器中先調用某些函數。

1.canvas

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 brower!</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>

js代碼:

定義一些變量:

//code from http://caibaojian.com/3-html5-animations.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){					//如果ani不爲null,則代表我們當前已經有了一個動畫
		      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;
		}

頁面加載的初始化方法:

//init
	    	function init(){
		   c=document.getElementById('canvas').getContext('2d');
		   drawCanvas();
		}

主調方法:

function drawCanvas(){
		   c.clearRect(0,0,c.canvas.width, c.canvas.height);	//清除Canvas(已顯示的),避免產生錯誤
		   c.save();						//保存當前座標值以及狀態,對應的類似“push”操作

		   drawGrass();						//畫背景
		   c.translate(carX,0);					//移動起點座標
		   drawCar();						//畫汽車(隱藏的canvas)
		   c.drawImage(w.canvas,0,carY);			//畫最終顯示的汽車
		   c.restore();						//恢復Canvas的狀態,對應的是類似“pop”操作
		   carX+=dx;						//重置汽車在X軸方向的位置,以模擬向前走
		   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);
		   //爲線性漸變指定漸變色,0表示漸變起始色,1表示漸變終止色
		   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;						//設置邊框的寬度,單位爲像素
		   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();

		}

由於原理簡單,並且代碼中作了詳細註釋,這裏就不一一講解!

2.CSS3

你將看到我們未通過一句JS代碼就完全實現了和上面一樣的動畫效果:

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>
      <footer></footer>
   </body>
</html>

CSS代碼:

 body
	 {
	    padding:0;
	    margin:0;
	 }

定義車身與輪胎轉到的動畫(你會看到基本每一個動畫都有四個版本的定義:原生版本/webkit【Chrome|Safari】/ms【爲了向後兼容IE10】/moz【FireFox】)

 /*定義動畫:從-400px的位置移動到1600px的位置 */
	 @keyframes carAnimation
	 {
	    0% { left:-400px; }		/* 指定初始位置,0%等同於from*/
	    100% { left:1600px; }	/* 指定最終位置,100%等同於to*/
	 }

	 /* Safari and Chrome */
	 @-webkit-keyframes carAnimation
	 {
	    0% {left:-400px; }
	    100% {left:1600px; }
	 }

	 /* Firefox */
	 @-moz-keyframes carAnimation
	 {
	    0% {left:-400; }
	    100% {left:1600px; } 
	 }

	 /*IE暫不支持,此處定義是爲了向後兼容IE10*/
	 @-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); }
	 }
 #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;		/*圓半徑*/
	    height:120px;		/* 2*radius=height */
	    width:120px;		/* 2*radius=width */
	    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;		/*設置右邊的輪胎距離邊緣的距離爲20*/
	 }

	 #backtire
	 {
	    left:20px;		/*設置左邊的輪胎距離邊緣的距離爲20*/
	 }

	 #grass
	 {
	    position:absolute;	/*背景絕對定位在容器中*/
	    width:100%;
	    height:130px;
	    bottom:0;
	    /*讓背景色線性漸變,bottom,表示漸變的起始處,第一個顏色值是漸變的起始值,第二個顏色值是終止值 */
	    background:linear-grdaient(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;
	 }

3.JQuery與CSS3

這是一個效果與兼容性俱佳的方式(特別對於IE9暫不支持CSS3而言)

HTML代碼(可以看到與CSS3中的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>
      <footer></footer>
   </body>
</html>

CSS:

<style>
         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軸)*/
	 }

	  /*車身*/
	 #chassis
	 {
	    position:absolute;
	    width:400px;
	    height:130px;
	    background:#FF9900;
	    border: 2px solid #FF6600;
	 }
	
	 /*輪胎*/
	 .tire
	 {
	    z-index:1;			/*同上,輪胎也應置於背景的上方*/
	    position:absolute;
	    bottom:0;
	    border-radius:60px;		/*圓半徑*/
	    height:120px;		/* 2*radius=height */
	    width:120px;		/* 2*radius=width */
	    background:#0099FF;		/*填充色*/
	    border:1px solid #3300FF;
	    -o-transform:rotate(0deg);	/*旋轉(單位:度)*/
	    -ms-transform:rotate(0deg);
	    -webkit-transform:rotate(0deg);
	    -moz-transform:rotate(0deg);
	 }

	 #fronttire
	 {
	    right:20px;		/*設置右邊的輪胎距離邊緣的距離爲20*/
	 }

	 #backtire
	 {
	    left:20px;		/*設置左邊的輪胎距離邊緣的距離爲20*/
	 }

	 #grass
	 {
	    position:absolute;	/*背景絕對定位在容器中*/
	    width:100%;
	    height:130px;
	    bottom:0;
	    /*讓背景色線性漸變,bottom,表示漸變的起始處,第一個顏色值是漸變的起始值,第二個顏色值是終止值 */
	    background:linear-grdaient(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;
	 }

      </style>

JS代碼:

首先引入在線API:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

實現動畫代碼(相當簡潔):

<script>
         $(function(){
	     var rot=0;
	     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={		/*該動畫由jQuery執行*/
		 left:1600		/*設置我們將移動到的最終位置*/
	 };

	     var rotate=function(){	/*該方法將被旋轉的輪子調用*/
		 rot+=2;
		 $('.tire').css(prefix,'rotate('+rot+'deg)');
	 };

	     var options={		/*將要被jQuery使用的參數*/
		 easing:'linear',	/*指定速度,此處只是線性,即爲勻速*/
		 duration:10000,	/*指定動畫持續時間*/
		 complete:function(){
		    $('#car').css(origin).animate(animation,options);
		 },
		 step:rotate
	 };

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

簡單講解:prefix首先識別出當前是哪個定義被採用了(-o?-moz?-webkit?-ms?),然後定義了動畫的起點位置和終點位置。接着,定義了設置旋轉角度的函數(該函數將在在動畫的每一步(step)中執行)。然後,定義了一個動畫,該定義方式導致了無限自循環調用!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章