requestAnimationFrame用法问题



我从http://my.opera.com/emoller/blog/2011/2011/20/requestanimationframeframe-for-smart-smart-er-er-er-animating/p.>

我正在尝试使用它。但不确定如何调用并使用它。有人可以给我一个简单的例子吗?我是这个HTML5动画的新手,所以您可以理解。

我将非常感谢任何帮助!该功能在下面..

    (function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelRequestAnimationFrame = window[vendors[x]+
          'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}())

只是将代码粘贴到您的JS或自己的文件中,然后将其放入您的渲染函数中。

requestAnimationFrame(yourrenderingfunction);

live demo

// requestAnimationFrame shim
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelRequestAnimationFrame = window[vendors[x]+
          'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}())

// Sprite unimportant, just for example purpose
function Sprite(){ 
    this.x = 0;
    this.y = 50;
}
Sprite.prototype.draw = function(){
    ctx.fillStyle = "rgb(255,0,0)";
    ctx.fillRect(this.x, this.y, 10, 10);
}

// setup
var canvas = document.getElementsByTagName("canvas")[0],
    ctx = canvas.getContext("2d");
canvas.width = 200;
canvas.height = 200;
//init the sprite
var sprite = new Sprite();
// draw the sprite and update it using request animation frame.
function update(){
    ctx.clearRect(0,0,200,200);
    sprite.x+=0.5;
    if(sprite.x>200){
        sprite.x = 0;            
    }
    sprite.draw();
    // makes it update everytime
    requestAnimationFrame(update);
}
// initially calls the update function to get it started
update();

最新更新