1

我从http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating获得了以下 RequestAnimationframe 函数

我正在尝试使用它。但不知道如何调用它和使用它。谁能给我一个简单的例子。我是这个 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);
        };
}())
4

1 回答 1

1

只需将该代码粘贴到您的 JS 或它自己的文件中,然后将其放在最底部的渲染函数中。

requestAnimationFrame(yourrenderingfunction);

现场演示

// 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();
于 2012-10-21T05:14:33.373 回答