Animation:startTime 属性
Animation 接口的 Animation.startTime 属性是一个双精度浮点值,表示动画播放应开始的计划时间。
动画的开始时间是其 timeline 在其目标 KeyframeEffect 被计划开始播放时的时间值。动画的开始时间最初是未解析的(意味着它是 null,因为它没有值)。
值
一个浮点数,表示以毫秒为单位的当前时间,如果未设置时间,则为 null。您可以读取此值来确定当前设置的开始时间,也可以更改此值以使动画在不同时间开始。
示例
同步不同的动画
在下面的示例中,我们可以通过为所有新动画猫设置与原始运行猫相同的 startTime 来同步它们。请注意,这仅在 Web Animation API 中才可能实现:使用 CSS 动画不可能同步两个独立的动画。
css
/* All cats have the same dimensions and the same sprite for a background image. */
.cat {
background: url("/shared-assets/images/examples/web-animations/cat_sprite.png") -600px
0 no-repeat;
height: 150px;
width: 100%;
}
/* The cats animated with CSS have their running animations set with CSS */
.cat.with-css {
animation: 0.75s steps(13, end) infinite run-cycle;
}
/*
The keyframes for the CSS running animation.
This moves the background image sprite around.
*/
@keyframes run-cycle {
from {
background-position: -600px 0;
}
to {
background-position: -600px -1950px;
}
}
js
const cssCats = document.getElementById("css-cats");
const waapiCats = document.getElementById("waapi-cats");
const insertCSSCat = document.getElementById("insert-css-cat");
const insertWAAPICat = document.getElementById("insert-waapi-cat");
// The same information as @keyframes run-cycle
const keyframes = [
{ backgroundPosition: "-600px 0" },
{ backgroundPosition: "-600px -1950px" },
];
// The same information as .cat.with-css
const timing = {
duration: 750,
iterations: Infinity,
easing: "steps(13, end)",
};
const catRunning = document
.getElementById("with-waapi")
.animate(keyframes, timing);
function createCat() {
const newCat = document.createElement("div");
newCat.classList.add("cat");
return newCat;
}
insertCSSCat.addEventListener("click", () => {
const newCat = createCat();
newCat.classList.add("with-css");
cssCats.insertBefore(newCat, insertCSSCat);
});
insertWAAPICat.addEventListener("click", () => {
const newCat = createCat();
const newAnimationPlayer = newCat.animate(keyframes, timing);
// set start time to be the same as the original .cat#with-waapi
newAnimationPlayer.startTime = catRunning.startTime;
waapiCats.insertBefore(newCat, insertWAAPICat);
});
时间精度降低
为了防止时序攻击和指纹识别,animation.startTime 的精度可能会根据浏览器设置进行舍入。在 Firefox 中,privacy.reduceTimerPrecision 首选项默认启用,默认为 2ms。您也可以启用 privacy.resistFingerprinting,在这种情况下,精度将为 100ms 或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds 的值(以较大者为准)。
例如,在降低时间精度的情况下,animation.startTime 的结果将始终是 0.002 的倍数,或者在启用 privacy.resistFingerprinting 的情况下是 0.1(或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds)的倍数。
js
// reduced time precision (2ms) in Firefox 60
animation.startTime;
// Might be:
// 23.404
// 24.192
// 25.514
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
animation.startTime;
// Might be:
// 49.8
// 50.6
// 51.7
// …
规范
| 规范 |
|---|
| Web 动画 # dom-animation-starttime |
浏览器兼容性
加载中…
另见
- Web Animations API
AnimationAnimation.currentTime用于获取动画的当前时间。