JS使用window.requestAnimationFrame()實現逐幀動畫

window.requestAnimationFrame() 方法告訴瀏覽器您希望執行動畫,並請求瀏覽器調用指定的函數在下一次重繪之前更新動畫。該方法使用一個回調函數作為參數,這個回調函數會在瀏覽器重繪之前調用。

如果你想做逐幀動畫的時候,你應該用這個方法。這就要求你的動畫函數執行會先於瀏覽器重繪動作。通常來說,被調用的頻率是每秒60次,但是一般會遵循W3C標準規定的頻率。如果是後臺標簽頁面,重繪頻率則會大大降低。

基本語法:

requestID = window.requestAnimationFrame(callback);  // Firefox 23 / IE10 / Chrome / Safari 7 (incl. iOS)
requestID = window.mozRequestAnimationFrame(callback);  // Firefox < 23
requestID = window.webkitRequestAnimationFrame(callback); // Older versions Chrome/Webkit 

瀏覽器支持情況:

下面通過兩個簡單的Demo介紹下window.requestAnimationFrame() 方法的使用

返回頂部

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>返回頂部</title>
  <style>
    .box {
      margin: 0 auto;
      width: 100%;
      height: 5000px;
    }
 
    .box1 {
      background: #b94a48;
    }
 
    .box2 {
      background: #fb8c00;
    }
 
    .box3 {
      background: #669900;
    }
 
    .box4 {
      background: #c0a16b;
    }
 
    .top {
      position: fixed;
      right: 20px;
      bottom: 20px;
      width: 40px;
      height: 40px;
      background: #8dc7ff;
      border-radius: 50%;
      cursor: pointer;
    }
  </style>
  <script>
    window.requestAnimationFrame = (function () {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function (callback) {
          window.setTimeout(callback, 6000 / 60)
        }
    })()
 
    window.cancelAnimFrame = (function () {
      return window.cancelAnimationFrame ||
        window.webkitCancelAnimationFrame ||
        window.mozCancelAnimationFrame ||
        window.oCancelAnimationFrame ||
        window.msCancelAnimationFrame ||
        function (callback) {
          window.clearTimeout(callback)
        }
    })()
 
    function scrollToTop() {
      let top = window.pageYOffset
      const duration = 320
      const step = top / (duration / (1000 / 60)) >> 0
      const fn = () => {
        if (top >= 0) {
          top -= step
          window.scrollTo(0, top)
          fn.rafTimer = window.requestAnimationFrame(fn)
        } else {
          window.scrollTo(0, 0)
          window.cancelAnimationFrame(fn.rafTimer)
        }
      }
      fn.rafTimer = window.requestAnimationFrame(fn)
    }
  </script>
</head>
<body>
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="top" onclick="scrollToTop()"></div>
</body>
</html>

錨點定位

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>錨點定位</title>
  <style>
    .top {
      margin: 100px auto;
      cursor: pointer;
    }
 
    .top1 {
      color: #b94a48;
    }
 
    .top2 {
      color: #fb8c00;
    }
 
    .top3 {
      color: #669900;
    }
 
    .top4 {
      color: #c0a16b;
    }
 
    .box {
      margin: 0 auto;
      width: 100%;
      height: 5000px;
    }
 
    .box1 {
      background: #b94a48;
    }
 
    .box2 {
      background: #fb8c00;
    }
 
    .box3 {
      background: #669900;
    }
 
    .box4 {
      background: #c0a16b;
    }
 
  </style>
  <script>
    window.requestAnimationFrame = (function () {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function (callback) {
          window.setTimeout(callback, 6000 / 60)
        }
    })()
 
    window.cancelAnimFrame = (function () {
      return window.cancelAnimationFrame ||
        window.webkitCancelAnimationFrame ||
        window.mozCancelAnimationFrame ||
        window.oCancelAnimationFrame ||
        window.msCancelAnimationFrame ||
        function (callback) {
          window.clearTimeout(callback)
        }
    })()
 
    function goPosition(index) {
      let top = 0
      let distance = document.getElementById(index).offsetTop
      const duration = 320
      const step = distance / (duration / (1000 / 60)) >> 0
      const fn = () => {
        if (distance >= top) {
          top += step
          window.scrollTo(0, top)
          fn.rafTimer = window.requestAnimationFrame(fn)
        } else {
          window.cancelAnimationFrame(fn.rafTimer)
        }
      }
      fn.rafTimer = window.requestAnimationFrame(fn)
    }
 
  </script>
</head>
<body>
<div class="top top1" onclick="goPosition('box1')">跳到第一個</div>
<div class="top top2" onclick="goPosition('box2')">跳到第二個</div>
<div class="top top3" onclick="goPosition('box3')">跳到第三個</div>
<div class="top top4" onclick="goPosition('box4')">跳到第四個</div>
<div id="box1" class="box box1"></div>
<div id="box2" class="box box2"></div>
<div id="box3" class="box box3"></div>
<div id="box4" class="box box4"></div>
</body>
</html>

網上技術大牛針對瀏覽器兼容封裝源碼:

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
 
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
 
// MIT license
 
(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.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                   || 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);
        };
}());

到此這篇關於JS使用window.requestAnimationFrame()實現逐幀動畫的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: