萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現緩動運動:目標點逼近算法、速度遞減、精準停止

緩動原理

每幀速度 = (目標位置 - 當前位置) / 系數。隨著距離縮小,速度遞減,形成「快進慢出」效果。
取整關鍵:正向 Math.ceil、反向 Math.floor,保證最後一幀能精確到達目標,避免無限逼近不等於。

完整代碼(可直接運行)

<!DOCTYPE html>
<html>
<head>
  <meta charset="gb2312">
  <title>緩動運動</title>
  <style>
    body { margin: 0; padding: 0; font: 12px/1.5 Arial; }
    #box { width: 100px; height: 100px; position: absolute; background: #06c; left: 0; }
  </style>
</head>
<body>
  <input id="btn" type="button" value="向右運動">
  <div id="box"></div>
  <br>
  <textarea id="log" cols="50" rows="10" style="margin-top:130px"></textarea>

  <script>
    window.onload = function() {
      var box = document.getElementById('box');
      var btn = document.getElementById('btn');
      var log = document.getElementById('log');
      var timer = null;

      btn.onclick = function() { startRun(300); };

      function startRun(target) {
        clearInterval(timer);
        timer = setInterval(function() {
          var speed = (target - box.offsetLeft) / 8;
          speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

          if (box.offsetLeft === target) {
            clearInterval(timer);
          } else {
            box.style.left = box.offsetLeft + speed + 'px';
          }
          log.value += box.offsetLeft + ',' + speed + '\n';
        }, 30);
      }
    };
  </script>
</body>
</html>

核心參數調節

參數影響建議範圍
除數 (代碼中 8)越大 → 緩動越緩慢、時間越長5-15
定時器間隔 (30ms)越小 → 幀率越高、CPU 佔用越大16ms (≈60fps) 或 30ms
目標值決定運動距離與總時長業務決定

現代化重構:requestAnimationFrame + 緩動函數庫

function easeOutQuad(t) { return t * (2 - t); } // t: 0-1

function animate(el, prop, target, duration, cb) {
  var start = performance.now();
  var from = parseFloat(getComputedStyle(el)[prop]);
  var isOpacity = prop === 'opacity';

  function frame(now) {
    var p = Math.min((now - start) / duration, 1);
    var eased = easeOutQuad(p);
    var val = from + (target - from) * eased;
    el.style[prop] = isOpacity ? val : val + 'px';
    if (p < 1) requestAnimationFrame(frame);
    else cb && cb();
  }
  requestAnimationFrame(frame);
}

// 使用
animate(box, 'left', 300, 800, function() { console.log('done'); });

擴展:彈性/彈跳/彈性緩動

  • 引入物理模型:位置、速度、加速度、阻尼、剛度
  • 或使用成熟庫:anime.js、gsap、motion-one
copyright © 萬盛學電腦網 all rights reserved