HyperFrames 的 Web Animations API
HyperFrames 可以通过其 waapi 运行时适配器来搜索 Web Animations API 动画。当您希望使用带有 JavaScript 创建的时间的原生浏览器关键帧且无需 GSAP 依赖时,WAAPI 非常有用。
契约
- 在 composition 初始化期间同步创建动画。
- 使用具有有限
duration和iterations的element.animate(...)。 - 使用
fill: "both"以便搜索的状态持久化。 - 创建动画后暂停它们,或让适配器在第一次搜索时暂停它们。
- 避免在渲染关键状态中使用回调和 Promise。
适配器调用 document.getAnimations(),将每个动画的 currentTime 设置为 HyperFrames 时间(毫秒),然后暂停它。
基本模式
<div id="orb" class="clip orb" data-start="2" data-duration="3" data-track-index="2"></div>
<script>
const orb = document.getElementById("orb");
const animation = orb.animate(
[
{ transform: "translate3d(-160px, 0, 0) scale(0.8)", opacity: 0 },
{ transform: "translate3d(0, 0, 0) scale(1)", opacity: 1, offset: 0.35 },
{ transform: "translate3d(120px, 0, 0) scale(1.08)", opacity: 1 },
],
{
duration: 3000,
delay: 2000,
easing: "cubic-bezier(0.2, 0, 0, 1)",
fill: "both",
iterations: 1,
},
);
animation.pause();
</script>
交错模式
document.querySelectorAll(".token").forEach((token, index) => {
const animation = token.animate(
[
{ transform: "translateY(24px)", opacity: 0 },
{ transform: "translateY(0)", opacity: 1 },
],
{
duration: 620,
delay: index * 80,
easing: "cubic-bezier(0.2, 0, 0, 1)",
fill: "both",
iterations: 1,
},
);
animation.pause();
});
良好用途
- 轻量级 DOM 动画,CSS 关键帧过于死板且 GSAP 不必要的情况。
- 从结构化数据生成的动画。
- 可以表示为关键帧、延迟和偏移的简单时间线。
避免
- 无限
iterations。 - 依赖
animation.finished来修改渲染关键 DOM。 - 使用
requestAnimationFrame、定时器或performance.now()运行单独的时钟。 - 当变换和透明度可以表达运动时,对布局属性进行动画。
- 假设剪辑本地开始时间是自动的。WAAPI 适配器搜索文档级别的动画时间;使用
delay模拟剪辑偏移,或在元素上创建动画,其可见性由 HyperFrames 时间控制。
验证
编辑 WAAPI composition 后:
npx hyperframes lint
npx hyperframes validate
鸣谢和参考
- HyperFrames 适配器源代码:
packages/core/src/runtime/adapters/waapi.ts。 - MDN Web Animations API 指南:https://developer.mozilla.org/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API
- MDN
Animation.currentTime:https://developer.mozilla.org/en-US/docs/Web/API/Animation/currentTime