DOM – Web Animation API


前言

以前写过相关的文章 . 但在项目种很少用到 Web Animation.

体会不到它的精髓. 目前的感觉是, 它对比 CSS Animation 更好控制. 比如它有 play, pause 这些功能.

缺点就是需要把 Style 逻辑写到 JS 里. 管理可能扣点分数.

参考

MDN – Using the Web Animations API

web animations api

【转载】Web Animation API 从入门到上座

使用Web Animations API让动画效果做加法

使用

先学会用 再学 Web Animation 会方便很多.

const keyframes: Keyframe[] = [
  { fontSize: "16px", color: "red", offset: 0 },
  { fontSize: "32px", color: "yellow", offset: 0.5 },
  { fontSize: "48px", color: "blue", offset: 1 },
];
const options: KeyframeAnimationOptions = {
  duration: 3000,
  fill: "forwards",
};

const animation = h1.animate(keyframes, options);

和 CSS Animation 写法差不多. Keyframes 定义 percentage 和 Style.

注意属性要用 camelCase 哦, 比如 fontSize, offset 就是 percentage. CSS 30% 这里就是 0.3

options 负责 duration, delay, fill 等等. duration 不支持 "100s" 这种写法哦. 用 number 表达最好.

当调用 .animate() 后动画就开始了.

还有一种以 style 属性出发的 keyframes 写法, 它长这样:

const keyframes2: PropertyIndexedKeyframes = {
  fontSize: ["16px", "32px", "48px"],
  color: ["red", "yellow", "blue"],
  offset: [0, 0.5, 1],
};

只是换一个写法而已, 功能完全是一样的.

常用操作

animation.addEventListener("finish", () => {
  console.log("end");
});

// animation.playbackRate = 2; // 双倍快
// animation.play(); // re-play or resume
// animation.pause(); // pause it

可以监听结束, pause, reply 调速度等等.

composition 还不支持哦

有个比较新的功能叫 composition, 但目前支持度不高. 就不研究闲了.

相关