首页 > 代码库 > 做动画的一大接口 requestAnimationFrame
做动画的一大接口 requestAnimationFrame
要实现动画效果,可以有以下几种实现:
1.setInterval setTimeout
2.css3 transition
3.requestAnimationFrame
requestAnimationFrame是浏览器自带的api,传入参数为动画效果的执行函数。
因为是浏览器自带的函数,所以执行动画的频率和浏览器显示频率是一致的(目前大部分浏览器显示频率为16.7ms,即1000/60ms),并且在切换到别的tab页之后,也就是页面没被激活时是不执行动画的。和setInterval setTimeout相比,执行堵塞的情况少。
回调函数可以自己定义,所以相对于css3的动画方法又有很多灵活性。比如动画执行曲线,完全可以自己定义。
举个使用requestAnimationFrame的栗子:
<!DOCTYPE html><html><head> <title>requestAnimationFrame</title></head><body> <canvas id="demo" width="500" height="500"></canvas></body><script> requestAnimationFrame = window.requestAnimationFrame || //webkit window.mozRequestAnimationFrame || //FF window.msRequestAnimationFrame || //IE window.oRequestAnimationFrame || //Opera function( callback ){ setTimeout( callback, 1000/60); }; function round(){ context.clearRect(0, 0, canvas.width, canvas.height); //清空画布 var time = new Date().getTime()*0.002; var x = Math.sin( time ) * 96 + 128; var y = Math.cos( time*0.9 )*96 +128; context.beginPath(); context.arc(x, y, 10, 0, 2*Math.PI); context.closePath(); context.fillStyle = ‘red‘; context.fill(); requestAnimationFrame( round ); } function start(){ canvas = document.getElementById(‘demo‘); context = canvas.getContext(‘2d‘); requestAnimationFrame( round ); } start();</script></html>
当然,人无完人,这个方法也是有缺陷的,那就是浏览器兼容性。RequestAnimationFrame浏览器支持情况如下:
IE10+
FF22+
chrome28+
Safari6+
Opera16+
不过有方案来处理兼容性问题,那就是将RequerstAnimationFrame方法和setTimeout结合:
(function(){ var lasttime = 0; var vendors = [‘webkit‘, ‘moz‘]; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; x ++){ window.requestAnimationFrame = window[ vendors[x] + ‘RequestAnimationFrame‘ ]; window.cancelRequestAnimationFrame = window[ vendors[x] + ‘CancelAnimationFrame‘ ]; } if( !window.requestAnimationFrame ){ window.requestAnimationFrame = function( callback ){ var curtime = new Date().getTime(); var timeToCall = Math.max(0, 16.7 - ( curtime - lasttime) ); var id = setTimeout(function(){ callback( curtime + timeToCall ); }, timeToCall); lasttime = curtime + timeToCall; return id; }; } if( !window.cancelRequestAnimationFrame ){ window.cancelRequestAnimationFrame = function( id ){ clearTimeout( id ); }; } })();
参考文章:
http://www.zhangxinxu.com/wordpress/2013/09/css3-animation-requestanimationframe-tween-%E5%8A%A8%E7%94%BB%E7%AE%97%E6%B3%95/
http://www.cnblogs.com/Wayou/p/requestAnimationFrame.html
http://www.cnblogs.com/rubylouvre/archive/2011/08/22/2148797.html