收藏文章 楼主

高性能写动画方法,get!

版块:网站建设   类型:普通   作者:小羊羔links   查看:506   回复:0   获赞:0   时间:2022-01-24 21:47:31

前言

说动前端动画,我们熟知的有两种

  1. CSS 动画
  2. (requestAnimation/setTimeout/setInterval + 属性改变) 动画

当然有人可能会说canvas动画,从运动本质了还是第二种。

今天说的是第三种 Web Animations API[1], 也有简称为 WAAPI 的。

与纯粹的声明式CSS不同,JavaScript还允许我们动态地将属性值设置为持续时间。对于构建自定义动画库和创建交互式动画,Web动画API可能是完成工作的完美工具。

举两个栗子

落球

点击之后,球体下落

ballFall2.gif
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)",
                duration2000,
                fill"forwards"
            })
});

直播的世界消息 者弹幕

这是一个我们项目中一个实际的例子, 直播的弹幕。
我们需要消息先运动到屏幕中间,消息最少需要在停留2秒,如果消息过长,消息还需要 匀速滚动 ,之后再滑出屏幕。

  1. 滑入
  2. 暂停,如果消息过长,消息还需要匀速滚动
  3. 滑出

难点就在于,暂停阶段,消息滚动的时间并不是确定的,需要计算。这个时候,纯CSS3的动画,难度就有些高了,采用 Web Animations API,天然的和JS亲和,那就简单多了。

先看看效果

shortDan.gif

代码也就简单的分为三段 滑入,暂停,滑出。
因为其天然支持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, {
        duration2000,
        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(0Math.floor(gapWidth / 200) * 1000);

    const translateX = duration > 0 ? gapWidth : 0;
    const kfsTxt = {
        transform: [`translateX(0px)``translateX(-${gapWidth}px)`]
    };
    await contentEl.animate(kfsTxt, {
        duration,
        delay2000,
        fill'forwards',
        easing'linear',
    }).finished;

    // 滑出
    const kfsOut = {
        transform: [`translateX(${centerX}px)``translateX(-${DANMU_WITH}px)`]
    };
    await danmuEl.animate(kfsOut, {
        duration2000,
        fill"forwards",
        easing'ease-in'
    }).finished;

    if (danmuEl) {
        stageEl.removeChild(danmuEl);
    }
    isAnimating = false
}

web Animations API 两个核心的对象

  1. KeyframeEffect 描述动画属性
  2. 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)']
},
duration3000fill'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();

kf2.gif

Animation[5]

提供播放控制、动画节点 源的时间轴。可以接受使用 KeyframeEffect[6] 构造函数创建的对象作为参数。

const box1ItemEl = document.querySelector(".box1");

const kyEffect = new KeyframeEffect(box1ItemEl, {
    transform: ['translateX(0)''translateX(200px)']
},
duration3000fill'forwards' })

const ani1 = new Animation(kyEffect);
ani1.play();

ani1.gif

常用的方法

  • cancel()[7] 取消
  • finish()[8] 完成
  • pause()[9] 暂停
  • play()[10] 播放
  • reverse()[11]  逆转播放方向

Animation 事件监听

监听有两种形式:

  1. event 方式因其继承于EventTarget,所有依旧有两种形式
animation.onfinish = function({
  element.remove();
}

animation.addEventListener("finish"function({
  element.remove();
}

  1. 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([ { opacity1 },
                  { opacity0.1offset0.7 },
                  { opacity0 } ],
                2000);

并非所有的关键帧都需要设置offset。 没有指定offset的关键帧将与相邻的关键帧均匀间隔。

对象形式

一个包含key-value键值的对象需要包含动画的属性和要循环变化的值数组

element.animate({
  opacity: [ 00.91 ],
  offset: [ 00.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()) // 暂停全部动画

优势

  1. 相对css动画更加灵活
  2. 相对requestAnimation/setTimeout/setInterval 动画,性能更好,代码更简洁
  3. 天然支持Promise,爽爽爽!!!

你有什么理由拒绝她呢?

对比 CSS Animation

动画参数属性键对照表

Web Animation APICSS
delayanimation-delay
durationanimation-duration
iterationsanimation-iteration-count
directionanimation-direction
easinganimation-timing-function
fillanimation-fill-mode

参数设置值上的区别

  1. duration 参数只支持毫秒
  2. 迭代次数无限使用的是 JS的Infinity,不是字符串 "infinite"
  3. 默认动画的贝塞尔是linear,而不是css的ease

兼容性

整体还不错,Safari偏差。
如果不行, 加个垫片 web-animations-js[20]

我们在实际的桌面项目上已经使用,非常灵活, nice!

总结

web Animations API 和 css动画,不是谁替换谁。结合使用,效果更佳。

复杂的逻辑动画,因为web Animations API和JS天然的亲和力,是更优的选择。

引用

Web Animations API[22]
Using the Web Animations API[23]
CSS Animations vs Web Animations API[24]

参考

[1]

Web Animations API: https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Animations_API

[2]

此页面仍未被本地化, 期待您的翻译!: **

[3]

Animationhttps://developer.mozilla.org/zh-CN/docs/Web/API/Animation

[4]

Element.animate: https://developer.mozilla.org/en-US/docs/Web/API/Element/animate

[5]

Animationhttps://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]

oncancelhttps://developer.mozilla.org/en-US/docs/Web/API/Animation/oncancel

[13]

onfinishhttps://developer.mozilla.org/en-US/docs/Web/API/Animation/onfinish

[14]

onremovehttps://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/

- EOF -

推荐阅读  点击标题可跳转

1、用three.js写一个下雨动画

2、十分钟教你用svg做出精美的动画!

3、7.1 万 Star!超实用,60 多种动画效果的 CSS 库


觉得本文对你有帮助?请分享给更多人

推荐关注「」,提升前端技能

点赞和在看就是最大的支持??

小羊羔锚文本外链网站长https://seo-links.cn 
回复列表
默认   热门   正序   倒序

回复:高性能写动画方法,get!

Powered by 小羊羔外链网 8.3.7

©2015 - 2024 小羊羔外链网

免费发软文外链 鄂ICP备16014738号-6

您的IP:44.212.26.248,2024-03-28 19:47:45,Processed in 0.05063 second(s).

支持原创软件,抵制盗版,共创美好明天!
头像

用户名:

粉丝数:

签名:

资料 关注 好友 消息