Проблема использования Requestanimationframe

Я получил следующую функцию RequestAnimationframe с сайта http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

Я пытаюсь использовать его. Но не уверен, как это назвать и использовать. Может кто-нибудь дать мне простой пример. Я новичок в этой анимации 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);
        };
}())

person user1655003    schedule 20.10.2012    source источник


Ответы (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();
person Loktar    schedule 21.10.2012
comment
Да да!! Большое спасибо Локтар. Вы сделали прекрасный пример для меня, чтобы понять :) Я отметил ваш ответ как правильный :) - person user1655003; 21.10.2012