web animations api
Web Animations API 允许同步和定时更改网页的呈现, 即DOM元素的动画。它通过组合两个模型来实现:时序模型(描述动画时间)和 动画模型(描述动画样式)。
基本用法:
下面是使用css实现一个动画:
#alice {
animation: aliceTumbling infinite 3s linear;
}
@keyframes aliceTumbling {
0% {
color: #000;
transform: rotate(0) translate3D(-50%, -50%, 0);
}
30% {
color: #431236;
}
100% {
color: #000;
transform: rotate(360deg) translate3D(-50%, -50%, 0);
}
}
现在让我们尝试使用Web动画API创建相同的动画:
//1.我们首先要做的是创建一个对应于我们的CSS @keyframes块的关键帧对象:
var aliceTumbling = [
{ transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
{ color: '#431236', offset: 0.3},
{ transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
];
//2.我们还需要创建一个定时属性的对象对应于爱丽丝动画中的值:
var aliceTiming = {
duration: 3000,
iterations: Infinity,
easing: linear
}
//3.执行动画
var aliceAnimation =document.getElementById("alice").animate(
aliceTumbling,
aliceTiming
)
//4.控制动画播放
aliceAnimation.pause()
/*
Animation.play() 播放动画
Animation.pause() 暂停动画
Animation.finish() 动画结束
Animation.cancel() 终止动画
Animation.reverse() 设置动画播放速度
Animation.playbackRate 到负值,所以它向后运行(改变动画的速度)
*/
接口对象:
1】Animation
提供播放控制、动画节点或源的时间轴。
//1.构造函数(Animation构造函数返回一个新的Animation对象实例)
var animation = new Animation(effect, timeline);
/*
参数
effect(可选)
将KeyframeEffect对象分配给动画。(在将来,其他类型的效果,如SequenceEffects或GroupEffects是可能被实现的,但现在,唯一的效果是KeyframeEffect。)
timeline(可选)
指定与动画关联的时间轴。(目前唯一可用的时间轴类型是DocumentTimeline对象,但在将来我会有与手势或滚动相关联的时间轴。)默认为Document.timeline。这也可以设置为null。
*/
//2.属性
/*
Animation.currentTime
动画的当前时间值(以毫秒为单位),无论是正在运行还是已暂停。如果动画缺少timeline或尚未播放,其值为null。
Animation.effect
获取或设置与此动画相关联的KeyframeEffect。
Animation.finished 只读
返回此动画的当前完成的状态。
Animation.id
获取或设置用于标识动画的字符串。
Animation.playState 只读
返回描述动画播放状态的枚举值。
Animation.playbackRate
返回或设置动画的播放速率。
Animation.ready 只读
返回此动画的当前就绪状态。
Animation.startTime
获取或设置动画播放应开始的预定时间。
Animation.timeline
获取或设置与此动画相关联的timeline。
*/
//3.事件处理程序
/*
Animation.oncancel
获取并设置取消事件的事件处理程序。
Animation.onfinish
获取并设置完成事件的事件处理程序。
*/
//4.方法
/*
Animation.cancel()
清除此动画的所有keyframeEffects,并中止播放。
Animation.finish()
设置动画中止播放。
Animation.pause()
暂停播放动画。
Animation.play()
开始或恢复播放动画,或者如果之前完成,则重新开始动画。
Animation.reverse()
反转播放动画,直到播放到动画开始时停止。 如果动画完成或未播放,它将从头到尾播放。
*/
var whiteRabbit = document.getElementById("rabbit");
var rabbitDownKeyframes = new KeyframeEffect(
whiteRabbit,
[
{ transform: 'translateY(0%)' },
{ transform: 'translateY(100%)' }
],
{ duration: 3000, fill: 'forwards' }
);
var rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline);
// On tap or click,
whiteRabbit.addEventListener("mousedown", downHeGoes, false);
whiteRabbit.addEventListener("touchstart", downHeGoes, false);
// Trigger a single-fire animation
function downHeGoes(event) {
// Remove those event listeners
whiteRabbit.removeEventListener("mousedown", downHeGoes, false);
whiteRabbit.removeEventListener("touchstart", downHeGoes, false);
// Play rabbit animation
rabbitDownAnimation.play();
}
2】KeyframeEffect
描述动画属性的集合。然后可以使用Animation构造函数传入该描述动画的集合进行播放。
var keyframes = new KeyframeEffect(element, keyframeSet, keyframeOptions);
var keyframes = new KeyframeEffect(sourceKeyFrames);
/*参数
element
要动画的DOM元素,或为null。
keyframeSet
关键帧对象或null。
keyframeOptions 可选
delay、direction、duration、easing、endDelay、fill、iterationStart、iterations、composite、iterationComposite
sourceKeyFrames
要克隆的KeyframeEffect对象
*/
例子:
var rabbitDownKeyframes = new KeyframeEffect(
whiteRabbit, // element to animate
[
{ transform: 'translateY(0%)' }, // keyframe
{ transform: 'translateY(100%)' } // keyframe
],
{ duration: 3000, fill: 'forwards' } // keyframe options
);
3】AnimationTimeline
Web动画API的AnimationTimeline
接口表示动画的时间轴。这个接口用于定义时间轴功能(被文档时间线
(en-US)和未来的时间轴类型所继承),但本身并不能被开发人员直接使用。无论何处当你要用AnimationTimeline
,都应该使用DocumentTimeline
或其他时间轴类型来实例化。
//1.属性
AnimationTimeline.currentTime 只读
//返回此时间轴的时间值(以毫秒为单位),若此时间轴未激活则返回null。
4】DocumentTimeline
Web Animations API 的 DocumentTimeline 接口表示动画时间线,包括默认的文档时间线(通过 Document.timeline 访问)。
const cats = document.querySelectorAll('.sharedTimelineCat');
//创建与当前浏览上下文的活动文档关联的新DocumentTimeline对象。
const sharedTimeline = new DocumentTimeline({ originTime: 500 });
//以原始时间500ms之后启动所有的cats元素的动画
for (const cat of cats) {
const catKeyframes = new KeyframeEffect(cat, keyframes, timing);
const catAnimation = new Animation(catKeyframes, sharedTimeline);
catAnimation.play();
}
/*
属性
此接口从其父类 AnimationTimeline 继承其属性。
AnimationTimeline.currentTime
返回此时间轴的时间值(以毫秒为单位),若此时间轴未激活则返回null。
*/
拓展功能:
Web Animations API 向 document 和 element 添加了一些新的功能。
扩展到 Document 的接口
-
DocumentTimeline
表示默认文档时间轴 -
返回当前对文档中的元素有效的
Animation
对象的数组。
扩展到 Element 的接口
-
用于在元素上创建和播放动画的快捷方式。 它返回创建的
Animation
对象实例。
React Demo:
import React, { useRef, useEffect } from "react";
import "./styles.css";
export default function App() {
const title = useRef<HTMLHeadingElement | null>(null);
const subtitle = useRef<HTMLHeadingElement | null>(null);
useEffect(() => {
//设置动画效果
let fadeAndMove = [
{ opacity: 0, transfrom: `translateY(-20px)` },
{ opacity: 1, transfrom: `translateY(0px)` }
];
//设置过渡
let titleTiming = { duration: 2000, easing: "ease-in-out" };
//执行动画,并返回当前动画描述对象
const TitleAnimaiton = title.current?.animate(fadeAndMove, titleTiming);
//设置动画效果
let expend = [
{ opacity: 0, letterSpacing: `-0.5em` },
{ opacity: 1, letterSpacing: `initial` }
];
//设置过渡
let subtitleTiming = {
//同个标题的动画的描述对象获取它的过渡时间
duration:
(TitleAnimaiton?.effect?.getComputedTiming().duration as number) / 2,
easing: "ease-in-out"
};
//执行动画并返回动画对象
const subtitleAnimaiton = subtitle.current?.animate(expend, subtitleTiming);
//暂停动画(动画不会继续播放)
subtitleAnimaiton?.pause();
//添加点击事件,并播放动画
function clickCallback() {
//playState:idle, running, paused, finished四种状态
if (subtitleAnimaiton?.playState !== "finished") {
subtitleAnimaiton?.play();
}
}
document.addEventListener("click", clickCallback, false);
//清除副作用
return () => {
TitleAnimaiton?.cancel();
subtitleAnimaiton?.cancel();
document.removeEventListener("click", clickCallback, false);
};
}, [title, subtitle]);
return (
<main>
<div className="container">
<h1 className="title" ref={title}>
Hello World
</h1>
<h2 className="subtitle" ref={subtitle}>
Start editing to see some magic happen!
</h2>
</div>
</main>
);
}
参考资料:
MDN Using the Web Animations API