<img src="http://cdn.tutorialzine.com/w... alt="Getting Started With The JavaScript Web Animation API" title="Getting Started With The JavaScript Web Animation API"/>javascript
在網頁中使用動畫提供了更好的用戶體驗,例如抽屜式菜單。css
目前爲止,web動畫能夠經過css3 transitions,css3 keyframes或者其餘的動畫庫(animate.css、Velocity、tween),如今咱們能夠使用js編寫更加自由的web動畫,那就是web animation。java
咱們分別用css3和web animation api寫個簡單的demo用來展現web animation的特性。ios
Democss3
css方法git
var square = document.getElementById('square'); square.addEventListener('click', function() { square.className += " animate"; }); .animate { animation-name: move-and-change-color; animation-duration: 0.4s; animation-fill-mode: forwards; } @keyframes move-and-change-color { 0% { transform: translateX(0); } 80% { transform: translateX(100px); background-color: #2196F3; } 100% { transform: translateX(100px); background-color: #EF5350; } }
Web Animation方法github
var moveAndChangeColor = [ { transform: 'translateX(0)', background: '#2196F3' // blue }, { offset: 0.8, transform: 'translateX(100px)', background: '#2196F3' // blue }, { transform: 'translateX(100px)', background: '#EF5350' // red } ]; //數組中的每一個對象表明一個動畫狀態 var circle = document.getElementById('circle'); circle.addEventListener('click', function() { circle.animate(moveAndChangeColor, { duration: 400, fill: 'forwards' }); });
經過上面的例子能夠簡單的對比出,css3方法侷限性較大,並不適合複雜的動畫,也不易於控制,而Web Animation Api適合複雜動畫,而且易於控制。web
var animation = elem.animate(transitions, options);
Web Animation Api 提供以下方法:chrome
pause() – 暫停動畫api
play() – 播放動畫
reverse() – 反向播放
finish() – 當即結束動畫
cancel() – 取消動畫並回到初始狀態
具體使用方法請看Demo
動畫運行的過程當中會經過animate返回動畫屬性對象,好比動畫播放速率-playbackrate,移步Demo
此外,咱們還能夠監聽finish
和cancel
事件作點其餘有意義的事情
spinnerAnimation.addEventListener('finish', function() { // Animation has completed or .finish() has been called. doSomething(); }); spinnerAnimation.addEventListener('cancel', function() { // Animation has been canceled. doSomething(); });
大部分chrome、firefox都支持Web Animation Api,其餘的例如ios、安卓都不支持,詳情請查看Caniuse
對於不支持的能夠是用polyfill