requestAnimationFrame代替interval实现更优质动画

只是在项目中尝试着代替了interval,据说效果比较好。先记录下。

代码片段:

var nextFrame=(function(){
  return window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  function(callback){ return setTimeout(callback , 1);};
})();

 

function doClose(){
  var animationFlag=true;
  var nowLeft=0;
  var nowRight=rightWidth;
  var timer=function(){
    if(nowLeft -everyChangeWidth>-1*leftWidth){
      nowLeft-=everyChangeWidth;
      nowRight+=everyChangeWidth;

      left.style.left=nowLeft+"px";
      right.style.width=nowRight+"px";
    }else{
      nowLeft=-1*leftWidth;
      nowRight=leftWidth+rightWidth;

      animationFlag=false;
      left.style.visibility="hidden";
      showbar.style.display="block";
      left.style.left=nowLeft+"px";
      right.style.width="100%";
      return;
    }
    browseListView.resize();
    if(animationFlag) nextFrame(timer);
  };
  timer();
}

 

原来:

function doClose(){
  var nowLeft=0;
  var nowRight=rightWidth;
  var timer=setInterval(function(){
    if(nowLeft -everyChangeWidth>-1*leftWidth){
      nowLeft-=everyChangeWidth;
      nowRight+=everyChangeWidth;

      left.style.left=nowLeft+"px";
      right.style.width=nowRight+"px";
    }else{
      nowLeft=-1*leftWidth;
      nowRight=leftWidth+rightWidth;

      clearInterval(timer);
      left.style.visibility="hidden";
      showbar.style.display="block";
      left.style.left=nowLeft+"px";
      right.style.width="100%";
      return;
    }
    listView1.resize();
  },timerValue);
}

优势:

  • 对于一个侦中对DOM的所有操作,只进行一次Layout和Paint。
  • 如果发生动画的元素被隐藏了,那么就不再去Paint。

使用方法:

  1. 调用requestAnimationFrame函数,传递一个callback参数,则在下一个动画帧时,会调用callback。
  2. 不传递参数地直接调用该函数,启动动画帧,下一个帧触发时,会同时触发window.onmozbeforepaint事件,可以通过注册该事件来进行动画。

第2种方法由于依赖于Firefox自己的事件,且beforepaint事件还没进入到标准中,所以不推荐使用,还是使用第1种方式比较好。此时,我们的动画逻辑可以变成这样:

  1. 记录当前时间startTime,作为动画开始的时间。
  2. 请求下一帧,带上回调函数。
  3. 下一帧触发时,回调函数的第一个参数为当前的时间,再与startTime进行比较,确定时间间隔ellapseTime。
  4. 判断ellapseTime是否已经超过事先设定的动画时间time,如果超过,则结束动画。
  5. 计算动画属性变化的差值differ = to – from,再确定在ellapseTime的时候应该变化多少step = differ / time * ellapseTime。
  6. 计算出现在应该变化到的位置Math.round(from + step),并重新对样式赋值。
  7. 继续请求下一帧。

摘自:http://www.cnblogs.com/rubylouvre/archive/2011/08/22/2148797.html

posted @ 2013-04-25 12:58  Ric.  阅读(342)  评论(0编辑  收藏  举报