web animations api

本文详细介绍了WebAnimationsAPI如何通过时序模型和动画模型实现网页动画,包括CSS与API创建动画的对比,关键帧对象、定时属性、Animation对象和其方法的使用示例,以及MDN示例和React应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()
反转播放动画,直到播放到动画开始时停止。 如果动画完成或未播放,它将从头到尾播放。
*/

我们来看一个mdn的例子

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();
}

img

2】KeyframeEffect

描述动画属性的集合。然后可以使用Animation构造函数传入该描述动画的集合进行播放。

keyframeSet

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动画APIAnimationTimeline接口表示动画的时间轴。这个接口用于定义时间轴功能(被文档时间线 (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 向 documentelement 添加了一些新的功能。

扩展到 Document 的接口
扩展到 Element 的接口

React Demo:

在react中使用Animation动画api

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>
  );
}

img

参考资料:

MDN Animation

MDN Web Animations API

MDN Using the Web Animations API

CSS Animation 与 Web Animation API 之争

b站视频

React Demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值