[置顶] HTML5 实现小车动画效果(Canvas/CSS3/JQuery)
HTML5正在變得越來越流行。在這個移動設備日益增長的時代,對來自Adobe的Flash插件的改造需求也正在快速增長。因為就在最近,Adobe宣布Flash將不再支持移動設備。這意味著,Adobe自身也認為對移動設備來講HTML5是一項重要的技術。而桌面系統的改變也是遲早的事。
HTML的一大劣勢就是對于多媒體技術支持的缺乏。在HTML中,你無法直接顯示一個視頻或在屏幕上繪畫。在HTML5中,隨著<video>與<canvas>元素的引進。這些元素給予開發者直接使用“純粹的”HTML來實現多媒體技術的可能性——僅需要寫一些Javascript代碼來配合HTML。在多媒體技術中,有一個基本的技術應該被支持——動畫。在HTML5中,有不少方式能夠實現該功能。
在這篇文章中,我僅將最新的<canvas>元素與即將到來的CSS3動畫技術進行比較。其他的可能性包括DOM元素或SVG元素的創建和動畫。這些可能性將不在本文中進行討論。從開始就應該注意到canvas技術在當前發布的大部分主流瀏覽器都給予了支持,而CSS3動畫僅在最新的FireFox與Chrome瀏覽器中才有實現的可能,下一個版本的IE也將提供對CSS3動畫的支持。(所以本文中所有演示代碼的效果,在Win 7系統下當前最新版的Chrome瀏覽器中都可實現,但在其他操作系統與其他瀏覽器中,并不一定能看到所有演示代碼的效果)。
這里我選擇了一個比較簡單的動畫:
PS:由于顯卡、錄制的幀間隔,以及可能你電腦處理器的原因,播放過程可能有些不太流暢或者失真!
分三種方式實現:
(1)???canvas元素結合JS
(2)???純粹的CSS3動畫(暫不被所有主流瀏覽器支持,比如IE)
(3)???CSS3結合Jquery實現
知道如何使用CSS3動畫比知道如何使用<canvas>元素更重要:因為瀏覽器能夠優化那些元素的性能(通常是他們的樣式,比如CSS),而我們使用canvas自定義畫出來的效果卻不能被優化。原因又在于,瀏覽器使用的硬件主要取決于顯卡的能力。目前,瀏覽器沒有給予我們直接訪問顯卡的權力,比如,每一個繪畫操作都不得不在瀏覽器中先調用某些函數。
?
讓我們從Canvas開始
HTML代碼:
<html> <head> <meta charset="UTF-8" /> <title>Animation in HTML5 using the canvas element</title> </head> <body οnlοad="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" οnclick="speed(-0.1);">Slower</button> <button type="button" οnclick="play(this);">Play</button> <button type="button" οnclick="speed(+0.1)">Faster</button> </div> </body> </html>JS代碼:
定義一些變量:
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(); }由于原理簡單,并且代碼中作了詳細注釋,這里就不一一講解!
該是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; } }
#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; }
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)中執行)。然后,定義了一個動畫,該定義方式導致了無限自循環調用!
本文,通過一個簡單的動畫實例,演示了HTML5下,實現動畫的幾種常見方式。
源碼下載
總結
以上是生活随笔為你收集整理的[置顶] HTML5 实现小车动画效果(Canvas/CSS3/JQuery)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CBOX直播故障:正在连接
- 下一篇: C#中全角与半角的转换