萬盛學電腦網

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

JavaScript 動畫核心知識點全解析:從基礎運動到多物體協同

前言

原生 JS 動畫是理解前端動畫本質的基石。雖然現代開發多使用 CSS Animation、Web Animations API 或 GSAP 等庫,但掌握定時器、緩動函數、幀率控制等核心概念,有助於深度排查動畫效能問題、實現高度自定義效果。

知識點一:基礎速度動畫

function linearMove(element, targetLeft, duration) {
  const start = performance.now();
  const startLeft = element.offsetLeft;
  const distance = targetLeft - startLeft;

  function step(now) {
    const elapsed = now - start;
    const progress = Math.min(elapsed / duration, 1);
    element.style.left = startLeft + distance * progress + 'px';
    if (progress < 1) requestAnimationFrame(step);
  }
  requestAnimationFrame(step);
}

關鍵:使用 requestAnimationFrame 替代 setInterval,配合時間戳計算進度,不受幀率波動影響。

知識點二:透明度漸變

function fade(element, targetOpacity, duration) {
  const start = performance.now();
  const startOpacity = parseFloat(getComputedStyle(element).opacity) || 1;
  const distance = targetOpacity - startOpacity;

  function step(now) {
    const progress = Math.min((now - start) / duration, 1);
    element.style.opacity = startOpacity + distance * progress;
    if (progress < 1) requestAnimationFrame(step);
  }
  requestAnimationFrame(step);
}

IE8- 需同時設定 filter: alpha(opacity=...),現代項目可忽略。

知識點三:緩動函數

線性動畫感覺生硬,引入緩動函數模擬物理真實感:

const Easing = {
  linear: t => t,
  easeInQuad: t => t * t,
  easeOutQuad: t => t * (2 - t),
  easeInOutQuad: t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
  // 更多:https://easings.net/
};

function animate(element, properties, duration, easingName = 'easeOutQuad') {
  const easing = Easing[easingName] || Easing.linear;
  const start = performance.now();
  const startValues = {};
  for (const prop in properties) {
    startValues[prop] = parseFloat(getComputedStyle(element)[prop]) || 0;
  }

  function step(now) {
    const progress = Math.min((now - start) / duration, 1);
    const eased = easing(progress);
    for (const prop in properties) {
      const distance = properties[prop] - startValues[prop];
      element.style[prop] = startValues[prop] + distance * eased + (prop === 'opacity' ? '' : 'px');
    }
    if (progress < 1) requestAnimationFrame(step);
  }
  requestAnimationFrame(step);
}

知識點四:多物體運動管理

每個元素維護獨立的定時器 ID、目標值、當前值,避免共用定時器導致相互干擾。

function startMove(element, targetProps, duration, easing) {
  // 取消該元素正在進行的動畫
  if (element._animTimer) cancelAnimationFrame(element._animTimer);

  const start = performance.now();
  const startProps = {};
  for (const p in targetProps) startProps[p] = parseFloat(getComputedStyle(element)[p]) || 0;

  function step(now) {
    const progress = Math.min((now - start) / duration, 1);
    const eased = Easing[easing](progress);
    for (const p in targetProps) {
      element.style[p] = startProps[p] + (targetProps[p] - startProps[p]) * eased + (p === 'opacity' ? '' : 'px');
    }
    if (progress < 1) element._animTimer = requestAnimationFrame(step);
    else element._animTimer = null;
  }
  element._animTimer = requestAnimationFrame(step);
}

知識點五:獲取計算樣式

function getStyle(element, prop) {
  return window.getComputedStyle ? getComputedStyle(element)[prop] : element.currentStyle[prop];
}
// 注意:getComputedStyle 回傳的寬高包含 padding、border(box-sizing: border-box 時),需注意 box-sizing 差異。

知識點六:任意屬性動畫(統一封裝)

將屬性名、目標值以物件傳入,支援 opacity、width、height、left、top、marginLeft 等任意數值屬性。對 opacity 特殊處理(不加 px、用 parseFloat)。

知識點七:鏈式動畫(回調 / Promise)

function animateAsync(element, props, duration, easing) {
  return new Promise(resolve => {
    animate(element, props, duration, easing);
    // 簡易輪詢檢查完成(實際應在 animate 內部 resolve)
    const check = setInterval(() => {
      if (!element._animTimer) { clearInterval(check); resolve(); }
    }, 16);
  });
}

// 使用
await animateAsync(box, { left: 200 }, 500, 'easeOutQuad');
await animateAsync(box, { top: 200 }, 500, 'easeInQuad');

知識點八:同時動畫(多屬性並行)

單次 animate 呼叫即可傳入多屬性物件,內部同一幀更新所有屬性,保證同步:

animate(box, { left: 300, top: 200, opacity: 0.5, width: 100 }, 800, 'easeInOutQuad');

效能優化清單

  • 優先使用 transform / opacity(合成層動畫,不觸發佈局/重繪)。
  • 使用 will-change: transform, opacity 提前提升合成層。
  • 避免在動畫循環中讀取佈局屬性(offsetWidth 等),造成強制同步佈局。
  • 大量元素動畫考慮 requestAnimationFrame 批次處理或 Web Workers + OffscreenCanvas。

總結

掌握這 8 大核心知識點,即可構建一個輕量、高效、可擴展的原生動畫引擎。實際專案中,簡單動畫首選 CSS,複雜序列、物理模擬、拖拽聯動等場景再考慮 JS 或 GSAP。

copyright © 萬盛學電腦網 all rights reserved