您的位置:首页 > 产品设计 > UI/UE

一个新的动画接口: requestAnimationFrame

2012-09-25 18:43 507 查看
转载地址: http://www.cnblogs.com/lbsgood/archive/2012/06/04/2534279.html
传统的 javascript 动画无非就是用setInterval函数来实现,这对于简单或对流畅性要求不高时不会有什么问题,但现在随着对用户体验的关注度不断提高,对动画的复杂程度和流畅性都有了更高的要求,传统动画显得捉襟见肘了。 为解决此问题浏览器提供了一个统一帧管理、提供监听帧的API,即requestAnimationFrame……

参考:http://www.cnblogs.com/rubylouvre/archive/2011/08/22/2148797.html

window.requestAnimFrame = (function(){
return  window.requestAnimationFrame       ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame    ||
window.oRequestAnimationFrame      ||
window.msRequestAnimationFrame     ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();

demo:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>requestAnimFrame</title>
<script>

// requestAnim shim layer by Paul Irish
window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback, /* DOMElement */ element){ window.setTimeout(callback, 1000 / 60); }; })();

// example code from mr doob : http://mrdoob.com/lab/javascript/requestanimationframe/
var canvas, context;

function init() {

canvas = document.createElement( 'canvas' );
canvas.width = 256;
canvas.height = 256;

context = canvas.getContext( '2d' );

document.body.appendChild( canvas );

}

function animate() {
requestAnimFrame( animate );
draw();

}

function draw() {

var time = new Date().getTime() * 0.002;
var x = Math.sin( time ) * 96 + 128;
var y = Math.cos( time * 0.9 ) * 96 + 128;

context.fillStyle = 'rgb(245,245,245)';
context.fillRect( 0, 0, 255, 255 );

context.fillStyle = 'rgb(255,0,0)';
context.beginPath();
context.arc( x, y, 10, 0, Math.PI * 2, true );
context.closePath();
context.fill();

}
window.onload = function(){
init()
animate();
}

</script>

<script>

</script>
</head>
<body>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: