美文网首页工作生活
十四、requestAnimationFrame

十四、requestAnimationFrame

作者: 懒羊羊3号 | 来源:发表于2019-07-03 15:10 被阅读0次

    setTimeout

    会进入事件循环队列,所以时间并不准确
    只能设定固定事件,与屏幕刷新时间不一定匹配

    requestAnimationFrame

    与setTimeout相比,requestAnimationFrame最大的优势是由系统来决定回调函数的执行时机。具体一点讲,如果屏幕刷新率是60Hz,那么回调函数就每16.7ms被执行一次,如果刷新率是75Hz,那么这个时间间隔就变成了1000/75=13.3ms,换句话说就是,requestAnimationFrame的步伐跟着系统的刷新步伐走。它能保证回调函数在屏幕每一次的刷新间隔中只被执行一次,这样就不会引起丢帧现象,也不会导致动画出现卡顿的问题。

    • 当页面隐藏或最小化当时候会停止动画,回到页面继续动画
    • 函数截流
    var progress = 0;
    //回调函数
    function render() {
        progress += 1; //修改图像的位置
        if (progress < 100) {
               //在动画没有结束前,递归渲染
               window.requestAnimationFrame(render);
        }
    }
    //第一帧渲染
    window.requestAnimationFrame(render);
    
    //mdn示例
    var start = null;
    var element = document.getElementById('SomeElementYouWantToAnimate');
    element.style.position = 'absolute';
    
    function step(timestamp) {
      if (!start) start = timestamp;
      var progress = timestamp - start;
      element.style.left = Math.min(progress / 10, 200) + 'px';
      if (progress < 2000) {
        window.requestAnimationFrame(step);
      }
    }
    
    window.requestAnimationFrame(step)
    

    相关文章

      网友评论

        本文标题:十四、requestAnimationFrame

        本文链接:https://www.haomeiwen.com/subject/jswqhctx.html