Animation: overallProgress 属性

overallProgressAnimation 接口的一个只读属性,它返回一个介于 01 之间的数字,表示动画在其完成状态下的总体进度。这是动画所有迭代的总进度,而不是单个迭代的进度。

overallProgress 在所有动画中都具有一致的行为,与 timeline 的类型无关。

一个介于 01 之间的数字,如果动画没有时间轴、不活跃、尚未播放,或者其 currentTime 被设置为非时间值,则返回 null

如果动画的 iterations 属性设置为 Infinity,或者其 currentTime 被设置为负值,overallProgress 将返回 0

如果动画的 duration 设置为 0overallProgress 将返回 1

示例

显示进度百分比

此演示使用 overallProgress 来创建“进度百分比”读数,并在动画运行时将其显示在屏幕上。

HTML

HTML 包含一个用于启动动画的 <button>,一个用于显示进度百分比的 <p> 元素,以及一个将要被动画化的 <div>

html
<button>Run animation</button>
<p class="progress">Progress: 0%</p>
<div class="box"></div>

演示的 CSS 提供了一些基本的样式,这些样式对于理解 JavaScript 的工作原理并不重要,因此为了简洁起见,我们将其隐藏了。

JavaScript

在 JavaScript 中,我们首先获取对 <button><p><div> 元素的引用。

然后我们创建

  • 一个 animation 变量,它将引用动画,一旦我们创建了它。
  • 一个 关键帧 数组
  • 一个包含时间属性的选项对象。
js
const btn = document.querySelector("button");
const progress = document.querySelector(".progress");
const box = document.querySelector(".box");

let animation;

const keyframes = [{ rotate: "0deg" }, { rotate: "360deg" }];

const timingProps = {
  duration: 3000,
  iterations: 1,
};

接下来,我们通过 addEventListener()<button> 添加一个 "click" 事件监听器,以便在按下按钮时:

  1. 使用 Element.animate() 启动动画,传入之前定义的关键帧和选项,并将返回的 Animation 实例赋值给 animation 变量。
  2. 通过 requestAnimationFrame() 方法运行一个名为 updateProgress() 的函数,该函数负责更新进度百分比显示。
js
btn.addEventListener("click", () => {
  // Animate the box
  animation = box.animate(keyframes, timingProps);
  // Start updating the progress percentage via rAF()
  requestAnimationFrame(updateProgress);
});

现在,我们来定义 updateProgress() 函数。它会查询 Animation.playState 来检查动画是否未完成。如果未完成,我们获取 overallProgress 的当前值,将其乘以 100 并向下取整,将其转换为一个完整的百分比数字,然后用它更新 <p> 元素的 textContent 值。然后,我们再次调用 requestAnimationFrame(updateProgress) 来重新运行进度百分比更新。

如果动画已完成,我们用“Finished!”消息替换进度百分比,并且不调用 requestAnimationFrame(updateProgress),因此进度百分比更新将停止。

js
function updateProgress() {
  // Check if the animation is finished
  if (animation.playState !== "finished") {
    // Convert overallProgress to a whole number percentage
    const progressPercentage = Math.floor(animation.overallProgress * 100);
    // Update the progress paragraph with the percentage
    progress.textContent = `Progress: ${progressPercentage}%`;
    // Only request the next frame if the animation is not finished
    requestAnimationFrame(updateProgress);
  } else {
    progress.textContent = "Finished!";
  }
}

结果

输出看起来像这样。尝试按下按钮,观看动画和相关的进度指示器运行。

规范

规范
Web 动画 Level 2
# dom-animation-overallprogress

浏览器兼容性

另见