<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