Table of Contents
一、远观:认识WAAPI
二、入门:从实例开始
三、进院:细数WAAPI众妙
动画回调与动画状态
时间控制与时间轴
多个动画
更高级的接口
四、登堂:官方案例
五、上座:移动端运行
六、品茗:参考文献
Home Web Front-end HTML Tutorial Web Animation API 从入门到上座_html/css_WEB-ITnose

Web Animation API 从入门到上座_html/css_WEB-ITnose

Jun 21, 2016 am 09:01 AM

一、远观:认识WAAPI

当我们谈及网页动画时,自然联想到的是CSS3动画、JS动画、SVG动画、APNG动画等技术以及jQuery.animate()等动画封装库,根据实际动画内容设计去选择不同的实现方式。然而,每个现行的动画技术都存在一定的缺点,如CSS3动画必须通过JS去获取动态改变的值,setInterval的时间往往是不精确的而且还会卡顿,APNG动画会带来文件体积较大的困扰,引入额外的动画封装库也并非对性能敏感的业务适用。目前情形对开发者而言,鱼和熊掌似乎不可兼得,既希望获得更强大便捷的动画控制能力,又希望性能和体验上足够流畅优雅,如果能有一种浏览器原生支持的通用的动画解决方案,那将是极好极好的呢。

W3C提出Web Animation API(简称WAAPI)正缘于此,它致力于集合CSS3动画的性能、JavaScript的灵活、动画库的丰富等各家所长,将尽可能多的动画控制由原生浏览器实现,并添加许多CSS不具备的变量、控制以及或调的选项。看起来一切都很棒,是不是以后我们在动画技术选型上可以一招鲜吃遍天了呢?接下来请跟我一起敲开Web Animation API的奇妙之门。

二、入门:从实例开始

WAAPI核心在于提供了

Element.animate()
Copy after login

方法,下面看个最简单的例子:

document.body.animate(    [{'background': 'red'}, {'background': 'green'}, {'background': 'blue'}]    , 3000);
Copy after login

使用Chrome 39以上的浏览器运行一下,页面背景色进行了红绿蓝的依次过渡,3s后结束。我们当然是不会满足于这么简单的控制参数,继续看下个例子:

  var dot = document.querySelector('.dot');  var frames = [    {transform: 'rotate(0deg) translate(80px)'},    {transform: 'rotate(360deg) translate(80px) '},  ];  var timing = {    duration: 2500,         //ms    delay: 0,               //ms    iterations: Infinity,   //1, 2, 3 ... Infinity    direction: 'alternate', //'normal', 'reverse'等    easing: 'ease-in-out',  //'linear', 'ease-in'等    fill: 'forwards',       //'backwards', 'both', 'none', 'auto'  };  dot.animate(frames, timing);
Copy after login

可以看到DOM节点具备全新的animate方法,第一个参数是关键帧数组frames[],对应CSS3中的@keyframes,每一帧的描述与css3极其类似;第二个参数是时间控制timing,包括有duration持续时间、iterations执行次数、direction动画方向、easing缓动函数等属性。是不是很像CSS3的语法,以上timing参数等同于:

.dot {  animation: frames 2500ms ease-in-out 0ms infinite alternate forwards;}
Copy after login

效果如下所示:

三、进院:细数WAAPI众妙

动画回调与动画状态

在最初的例子中,我们可以定义一个对象来接收Element.animate()的返回值,如:

var player = document.body.animate(/* ... */);
Copy after login

player即成为该动画返回的一个“动画播放器”对象,同时动画开始播放。我们需要了解动画当前的状态,可以通过该对象的只读属性playState来获得:

console.log(player.playState); //"running","paused","finished"...
Copy after login

播放器共有五种状态,除了代码中注释的三种基本状态,还包括"idle"表示恢复到初始状态,"pending"表示播放或者暂停即将发生时。

播放器可以通过四种方法可以改变动画当前的状态。

player.pause(); //"paused"player.play();  //"running"player.cancel(); //"idle"player.finish(); //"finished"
Copy after login

与CSS3动画类似,player可以为动画自然结束或者手动结束时指定一个onfinish函数。

player.onfinish = function(e) {    // ...}
Copy after login

请注意,设置播放次数Infinity的动画没有自然结束的时机去调用onfinish函数。

时间控制与时间轴

播放器player具有一个读写属性playbackRate,用于控制动画的播放速度。

var player = element.animate(/* ... */);console.log(player.playbackRate); //1player.playbackRate = 2; 
Copy after login

playbackRate默认值为1,可以通过设置更大的整数使得动画加速,也可以通过设置大于零的小数来使得动画减缓播放速度。

player还具有两个与时间相关的读写属性currentTime和startTime。前者返回动画当前过去的毫秒数,它的最大值是timing参数设置的delay+(duration*iterations),而设置Infinity的动画没有currentTime的最大值。

当设置了playbackRate时,动画的currentTime并不会发生变化,真正变化的是时间轴,播放速度改变使得时间轴被相应拉伸或者压缩。

播放器可以调用reverse()倒叙播放动画,由时间轴的终点走向起点,动画结束时currentTime的值回到0。

player.onfinish = function() {    player.reverse();}
Copy after login

多个动画

CSS3动画是可以同时指定多个keyframes动画到一个DOM节点上,WAAPI同样具备应用多个动画的能力。在一个元素上多次调用animate方法,即实现了一个元素多个动画:

var animated = document.getElementById('toAnimate');var pulseKeyframes, activateKeyframes, haveFunKeyframes;var pulse = animated.animate(pulseKeyframes, 1000); var activate = animated.animate(activateKeyframes, 3000);var haveFunWithIt = animated.animate(haveFunKeyframes, 2500);
Copy after login

每个子动画也拥有独立的timing参数,以及独立的动画状态(播放、停止、完成、取消)和独立的时间轴(启动时间、播放速度和结束时间),方便动画进行细节控制。

更高级的接口

WAAPI还拥有timeline属性,对动画进行分组和排序的能力,以及沿自定义路径移动(再也不是SVG的天下了)的能力,光这一点就足够令人激动不已,然而篇幅有限于是下回再表。

四、登堂:官方案例

Codelabs 越来越多基于WAAPI的Codelabs实例涌现,这些实例非常适合初接触WAAPI的同学作为开始的范例。 [https://github.com/web-animations/web-animations-codelabs]

Google’s demos 如果你希望用WAAPI挑战更炫酷的动画,特别是遵循Material Design风格的动画效果,这将是不错的灵感来源。 [http://web-animations.github.io/web-animations-demos]

五、上座:移动端运行

看到这里,相信你已经不只一次体验到WAAPI带来的惊喜。作为一名彻头彻尾的移动端H5开发,我当然也想把WAAPI应用到移动业务上去服务用户…什么?手机上怎么没效果!

[http://caniuse.com/#feat=web-animation]

为了在现代浏览器厂商还没完全跟进到位的时候抢先用上WAAPI,我们可以选择引入针对Web Animation API的Polyfill库[https://github.com/web-animations/web-animations-js],从而在IE/Firefox/Safari等浏览器上体验到WAAPI的精彩。

<scriptsrc="https://cdn.jsdelivr.net/web-animations/latest/web-animations.min.js"></script><script>  document.body.animate([    {'background': 'red'},    {'background': 'green'}  ], 1000);</script>
Copy after login

移动端浏览器,Android 5.0以上的Android Browser和Chrome for Android本身就已经支持WAAPI了,加上Polyfill之后,iOS的Safari也支持了。别忘了,还有我大手Q的X5内核浏览器。

至此,小伙伴们终于露出欣慰的笑容。敬请期待下篇《Web Animation API 从上座到书墨》。

六、品茗:参考文献

  1. W3C Spec:https://w3c.github.io/web-animations/
  2. 《Let’s talk about the Web Animations API》:http://danielcwilson.com/blog/2015/07/animations-intro/
  3. Google's Demo:http://web-animations.github.io/web-animations-demos/
  4. codelabs: https://github.com/web-animations/web-animations-codelabs
  5. Polyfill: https://github.com/web-animations/web-animations-js
  6. Resources:https://developers.google.com/web/updates/2015/10/web-animations-resources
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

How do I use the HTML5 <time> element to represent dates and times semantically? How do I use the HTML5 <time> element to represent dates and times semantically? Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 &lt;time&gt; element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

See all articles