欢迎来到码农权的博客 MaNongGeGe.|

requestAnimationFrame优化动画

  1. requestAnimationFrame优化动画
  • 总结:
  • requestAnimationFrame与setInterval的区别
  • setInterval是在任务队列里执行的,也就是说 上一帧没有执行完下一帧不可能执行。
  • 而requestAnimationFrame是在差异队列里执行的,也就是说没有延迟。
  • requestAnimationFrame可以准时执行每一帧
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #main {
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: #abcdef;
    }
  </style>
</head>
<body>
  <div id="main"></div>
  <script>
    // requestAnimationFrame优化动画(兼容性极差)
    // requestAnimationFrame与setInterval的区别
    //    setInterval是在任务队列里执行的,也就是说 上一帧没有执行完下一帧不可能执行。
    //    而requestAnimationFrame是在差异队列里执行的,也就是说没有延迟。
    // requestAnimationFrame可以准时执行每一帧
    // cancelAnimationFrame相当于clearTimeout

    // 处理兼容
    window.requestAnimationFrame = ((callback)=> {
      return window.requestAnimationFrame || function (id) {
        setTimeout(callback, 1000 / 60)
      }
    })();

    window.cancelAnimationFrame = (()=> {
      return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function (id) {
        window.clearTimeout(id);
      }
    })()

    let timer = null;
    const move = ()=> {
      console.log(1)
      const square = document.getElementById("main");
      if(square.offsetLeft > 700) {
        cancelAnimationFrame(timer);
        return;
      };
      square.style.left = `${square.offsetLeft + 20}px`;
      timer = requestAnimationFrame(move);
    }
  </script>
</body>
</html>

本文作者:HuangBingQuan

本文链接:https://www.cnblogs.com/bingquan1/p/17591857.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   HuangBingQuan  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 不将就 码农权
  2. 2 Bleeding Love 码农权
  3. 3 想你念你 码农权
想你念你 - 码农权
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

Not available