前言
说动前端动画,我们熟知的有两种
-
CSS 动画 -
(requestAnimation/setTimeout/setInterval + 属性改变) 动画
当然有人可能会说canvas动画,从运动本质了还是第二种。
今天说的是第三种 Web Animations API[1], 也有简称为 WAAPI 的。
与纯粹的声明式CSS不同,JavaScript还允许我们动态地将属性值设置为持续时间。对于构建自定义动画库和创建交互式动画,Web动画API可能是完成工作的完美工具。
举两个栗子
落球
点击之后,球体下落

const ballEl = document.querySelector(".ball");
ballEl.addEventListener("click", function () {
let fallAni = ballEl.animate({
transform: ['translate(0, 0)', 'translate(20px, 8px)', 'translate(50px, 200px)']
}, {
easing: "cubic-bezier(.68,.08,.89,-0.05)",
duration: 2000,
fill: "forwards"
})
});
直播的世界消息或者弹幕
这是一个我们项目中一个实际的例子, 直播的弹幕。
我们需要消息先运动到屏幕中间,消息最少需要在停留2秒,如果消息过长,消息还需要 匀速滚动
,之后再滑出屏幕。
-
滑入 -
暂停,如果消息过长,消息还需要匀速滚动 -
滑出
难点就在于,暂停阶段,消息滚动的时间并不是确定的,需要计算。这个时候,纯CSS3的动画,难度就有些高了,采用 Web Animations API,天然的和JS亲和,那就简单多了。

代码也就简单的分为三段:滑入,暂停,滑出。
因为其天然支持Promise, 代码很简洁,逻辑也很清晰。
async function startAnimate() {
// 滑入
const totalWidth = stageWidth + DANMU_WITH;
const centerX = stageWidth * 0.5 - DANMU_WITH * 0.5;
const kfsIn = {
transform: [`translateX(${totalWidth}px)`, `translateX(${centerX}px)`]
}
await danmuEl.animate(kfsIn, {
duration: 2000,
fill: 'forwards',
easing: 'ease-out'
}).finished;
// 暂停部分
const contentEl = danmuEl.querySelector(".danmu-content");
const itemWidth = contentEl.getBoundingClientRect().width;
const gapWidth = Math.max(0, itemWidth - DANMU_WITH);
const duration = Math.max(0, Math.floor(gapWidth / 200) * 1000);
const translateX = duration > 0 ? gapWidth : 0;
const kfsTxt = {
transform: [`translateX(0px)`, `translateX(-${gapWidth}px)`]
};
await contentEl.animate(kfsTxt, {
duration,
delay: 2000,
fill: 'forwards',
easing: 'linear',
}).finished;
// 滑出
const kfsOut = {
transform: [`translateX(${centerX}px)`, `translateX(-${DANMU_WITH}px)`]
};
await danmuEl.animate(kfsOut, {
duration: 2000,
fill: "forwards",
easing: 'ease-in'
}).finished;
if (danmuEl) {
stageEl.removeChild(danmuEl);
}
isAnimating = false
}
web Animations API 两个核心的对象
-
KeyframeEffect 描述动画属性 -
Animation 控制播放
KeyframeEffect
描述动画属性的集合,调用keyframes及 Animation Effect Timing Properties[2]。然后可以使用 `Animation`[3] 构造函数进行播放。
其有三种构建方式,着重看第二种,参数后面说。
new KeyframeEffect(target, keyframes);
new KeyframeEffect(target, keyframes, options)
new KeyframeEffect(source)
当然我们可以显示的去创建 KeyframeEffect, 然后交付给Animation去播放。但是我们通常不需要这么做, 有更加简单的API, 这就是接后面要说的 Element.animate[4]。
看一个KeyframeEffect复用的例子,new KeyframeEffect(kyEffect)
基于当前复制,然后多处使用。
const box1ItemEl = document.querySelector(".box1");
const box2ItemEl = document.querySelector(".box2");
const kyEffect = new KeyframeEffect(null, {
transform: ['translateX(0)', 'translateX(200px)']
},
{ duration: 3000, fill: 'forwards' })
const ky1 = new KeyframeEffect(kyEffect);
ky1.target = box1ItemEl;
const ky2 = new KeyframeEffect(kyEffect);
ky2.target = box2ItemEl;
new Animation(ky1).play();
new Animation(ky2).play();

`Animation`[5]
提供播放控制、动画节点或源的时间轴。可以接受使用 KeyframeEffect[6] 构造函数创建的对象作为参数。
const box1ItemEl = document.querySelector(".box1");
const kyEffect = new KeyframeEffect(box1ItemEl, {
transform: ['translateX(0)', 'translateX(200px)']
},
{ duration: 3000, fill: 'forwards' })
const ani1 = new Animation(kyEffect);
ani1.play();

常用的方法
-
`cancel()`[7] 取消 -
`finish()`[8] 完成 -
`pause()`[9] 暂停 -
`play()`[10] 播放 -
`reverse()`[11] 逆转播放方向
Animation 事件监听
监听有两种形式:
-
event 方式因其继承于EventTarget,所有依旧有两种形式
animation.onfinish = function() {
element.remove();
}
animation.addEventListener("finish", function() {
element.remove();
}
-
Promise形式
animation.finished.then(() =>
element.remove()
)
比如一个很有用的场景,所有动画完成后:
Promise.all( element.getAnimations().map(ani => ani.finished)
).then(function() {
// do something cool
})
常用事件回调
-
`oncancel`[12] 取消 -
`onfinish`[13] 完成 -
`onremove`[14] 删除
便捷的 Element.animate[15]
任何 Element[16]都具备该方法, 其语法:
animate(keyframes, options)
其参数和 new KeyframeEffect(target, keyframes, options)
的后两个参数基本一样, 返回的是一个Animation对象。
第一个参数 keyframes
keyframes有两种形式,一种是数组形式,一种是对象形式。
数组形式
一组对象(关键帧) ,由要迭代的属性和值组成。
关键帧的偏移可以通过提供一个offset
来指定 ,值必须是在 [0.0, 1.0] 这个区间内,且须升序排列。简单理解就是进度的百分比的小数值。
element.animate([ { opacity: 1 },
{ opacity: 0.1, offset: 0.7 },
{ opacity: 0 } ],
2000);
并非所有的关键帧都需要设置offset
。 没有指定offset
的关键帧将与相邻的关键帧均匀间隔。
对象形式
一个包含key-value键值的对象
需要包含动画的属性和要循环变化的值数组
。
element.animate({
opacity: [ 0, 0.9, 1 ],
offset: [ 0, 0.8 ], // [ 0, 0.8, 1 ] 的简写
easing: [ 'ease-in', 'ease-out' ],
}, 2000);
第二个参数 options
和new KeyframeEffect(target, keyframes, options)
的第三个参数基本一致,但是多了一个可选属性,就是id,用来标记动画,也方便 在Element.getAnimations[17]结果中精确的查找。
参数名 | 含义 |
---|---|
delay |
延迟动画开始的毫秒数。默认为0。 |
direction |
动画运动方向 |
duration |
动画每次迭代完成所需的毫秒数。默认为0 |
easing |
动画曲线函数,可以自定义 |
endDelay |
动画结束后要延迟的毫秒数。这主要用于基于另一个动画的结束时间对动画进行排序。默认为0。 |
fill |
动画结束后属性值的状态 |
iterationStart |
描述动画应该在迭代的什么时候开始。0.5表示在第一次迭代中途开始,使用这个值集,一个有两次迭代的动画将在第三次迭代中途结束。默认为0.0 |
iterations |
动画应该重复的次数。默认值为1,也可以取一个值 Infinity,使其在元素存在期间重复。 |
composite |
动画和其他单独的动画之间组合。这是个高级特性,默认是replace,就是替换提起的动画。 |
iterationComposite |
动画的属性值变化如何在每次动画迭代时累积或相互覆盖 |
后续四个特性相对高级,掌握好了可以玩出花来,本章主要讲基本知识,后续会出高级版本。
更多细节可以参见 KeyframeEffect[18]
Element.getAnimations[19]
我们通过Element.animate或者创建Animation给Element添加很多动画,通过这个方法可以获得所有Animation的实例。
在需要批量修改参数,或者批量停止动画的时候,那可是大杀器。
比如批量暂停动画:
box1ItemEl.getAnimations()
.forEach(el=> el.pause()) // 暂停全部动画
优势
-
相对css动画更加灵活 -
相对requestAnimation/setTimeout/setInterval 动画,性能更好,代码更简洁 -
天然支持Promise,爽爽爽!!!
你有什么理由拒绝她呢?
对比 CSS Animation
动画参数属性键对照表
Web Animation API | CSS |
---|---|
delay | animation-delay |
duration | animation-duration |
iterations | animation-iteration-count |
direction | animation-direction |
easing | animation-timing-function |
fill | animation-fill-mode |
参数设置值上的区别
-
duration
参数只支持毫秒 -
迭代次数无限使用的是 JS的 Infinity
,不是字符串"infinite"
-
默认动画的贝塞尔是 linear
,而不是css的ease
兼容性
整体还不错,Safari偏差。
如果不行, 加个垫片 web-animations-js[20]。
总结
web Animations API 和 css动画,不是谁替换谁。结合使用,效果更佳。
复杂的逻辑动画,因为web Animations API和JS天然的亲和力,是更优的选择。
写在最后
你的一赞一评就是我前行的最大动力。
技术交流群请到 这里来[21]。或者添加我的微信 dirge-cloud,一起学习。
引用
Web Animations API[22]
Using the Web Animations API[23]
CSS Animations vs Web Animations API[24]
参考资料
Web Animations API: https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Animations_API
[2]
此页面仍未被本地化, 期待您的翻译!: **
[3]
Animation
: https://developer.mozilla.org/zh-CN/docs/Web/API/Animation
[4]
Element.animate: https://developer.mozilla.org/en-US/docs/Web/API/Element/animate
[5]
Animation
: https://developer.mozilla.org/zh-CN/docs/Web/API/Animation
[6]
KeyframeEffect: https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/KeyframeEffect
[7]
cancel()
: https://developer.mozilla.org/zh-CN/docs/Web/API/Animation/cancel
[8]
finish()
: https://developer.mozilla.org/zh-CN/docs/Web/API/Animation/finish
[9]
pause()
: https://developer.mozilla.org/zh-CN/docs/Web/API/Animation/pause
[10]
play()
: https://developer.mozilla.org/zh-CN/docs/Web/API/Animation/play
[11]
reverse()
: https://developer.mozilla.org/zh-CN/docs/Web/API/Animation/reverse
[12]
oncancel
: https://developer.mozilla.org/en-US/docs/Web/API/Animation/oncancel
[13]
onfinish
: https://developer.mozilla.org/en-US/docs/Web/API/Animation/onfinish
[14]
onremove
: https://developer.mozilla.org/en-US/docs/Web/API/Animation/onremove
[15]
Element.animate: https://developer.mozilla.org/en-US/docs/Web/API/Element/animate
[16]
Element: https://developer.mozilla.org/en-US/docs/Web/API/Element
[17]
Element.getAnimations: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
[18]
KeyframeEffect: https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/KeyframeEffect
[19]
Element.getAnimations: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
[20]
web-animations-js: https://github.com/web-animations/web-animations-js
[21]
https://juejin.cn/pin/6994350401550024741: https://juejin.cn/pin/6994350401550024741
[22]
Web Animations API: https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Animations_API
[23]
Using the Web Animations API: https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API
[24]
CSS Animations vs Web Animations API: https://css-tricks.com/css-animations-vs-web-animations-api/
原文始发于微信公众号(成长的程序世界):复杂web动画,不慌,选择 web Animations API
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/268001.html