2012-10-20 47 views
1

我从http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animatingRequestanimationframe使用率问题

得到了以下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); 
     }; 
}()) 

回答

1

只是,代码粘贴到您的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(); 
+1

没错没错!非常感谢Loktar。你做了一个完美的例子,我听不懂:)我已经打上你的答案是正确的:) – user1655003