requestAnimationFrame,更优的动画

by Bentz on March 13, 2011

浏览器上的动画,通常都是用定时器完成,每隔一段时间改变一下元素属性。但是定时器太古板,不管是否当前标签,都会吃掉部分cpu资源。所幸现代浏览器对开发者友好,将这些脏活抗了去,还做了优化。现在,我们要做的只是调用API,就能减少动画过程中的repaint、reflow,减少cpu占用。

废话不多说,直接上代码

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

    // usage:
    // instead of setInterval(render, 16) ....

    (function animloop(){
      render();
      requestAnimFrame(animloop, element);
    })();

参考: requestAnimationFrame for smart animating

Leave your comment

Required.

Required. Not published.

If you have one.