anime.js 动画_用Anime.js动画化DOM

作者:神秘网友 发布时间:2020-09-03 03:33:08

anime.js 动画_用Anime.js动画化DOM

anime.js 动画_用Anime.js动画化DOM

anime.js 动画

anime.js 动画_用Anime.js动画化DOM

If you’re looking for a fast and lightweight animation library, Anime.js by Julian Garnier is an option you’d like to consider.

如果您正在寻找快速且轻便的动画库,那么Julian Garnier的Anime.js是您想要考虑的选择。

This is the first of a series of articles about tools for dynamic DOM animation, including SVG graphics. I don’t plan to include specialized canvas-WebGL animation libraries or SVG-specific animation libraries. However, if a library is great at animating HTML elements on a webpage (and ideally also SVG graphics), I will consider it for inclusion in this series.

这是有关动态DOM动画工具(包括SVG图形)的系列文章的第一篇。 我不打算包含专门的canvas-WebGL动画库或SVG特定的动画库。 但是,如果图书馆擅长为网页上HTML元素(最好是SVG图形)制作动画,我将考虑将其包含在本系列中。

It is not my intention to dissect each library and delve deeply into its code. Instead, I am going to approach each library from the perspective of someone who mainly works with CSS but would like to explore what JavaScript has to offer when it comes to animating the DOM. Therefore, I will be looking for a tool that is great at manipulating the DOM by dynamically adding and removing CSS styles and/or classes for the purposes of animation by means of a syntax that feels familiar to a CSS developer.

我无意剖析每个库并深入研究其代码。 取而代之的是,我将从一个主要使用CSS但希望探究JavaScript动画DOM的人的角度来研究每个库。 因此,我将寻找一种通过XML开发人员熟悉的语法动态地添加和删除CSS样式和/或类(以动画为目的),从而很好地操作DOM的工具。


As Sarah Drasner explains, when talking about web animation, a useful distinction is between user interface/user experience animation and standalone animation.

正如Sarah Drasner解释的那样 ,在谈论网络动画时,有用的区别在于用户界面/用户体验动画独立动画之间

Research shows how human perception understands the world better on the basis of moving images. This means that we can understand and assimilate information better when it is presented to us in a moving scene rather than in the form of an image or even a series of static images.

研究表明,人类感知如何基于运动图像更好地理解世界。 这意味着,当信息以动态场景呈现给我们时,而不是以图像甚至一系列静态图像的形式呈现给我们,我们可以更好地理解和吸收信息。

UI/UX animation serves the purpose of aiding users as they navigate a website, absorb information on a webpage, or perform a specific task, e.g., signing up for a newsletter, adding an item to the shopping cart, etc.

UI / UX动画的目的是在用户浏览网站,吸收网页上的信息或执行特定任务(例如注册时事通讯,将商品添加到购物车等)时帮助用户。

By contrast, standalone animation is…


Used to illustrate concepts in the body of the page, either alongside or on it’s own.


Sarah Drasner — CSS Conference slides

Sarah Drasner — CSS会议幻灯片

Here’s an amazing CodePen demo by Sarah to illustrate the point.

这是Sarah出色的CodePen演示 ,以说明这一点。

The distinction is important because when you’re animating user interfaces, your aim is to help users perform those tasks which go towards meeting the website’s goals. Instead, when creating a standalone animation, you set out to express a certain concept as fully as possible.

区别很重要,因为在为用户界面添加动画时,您的目的是帮助用户执行那些有助于实现网站目标的任务 。 相反,在创建独立动画时,您打算尽可能完整地表达某个概念

That said, both kinds of animation are made for people to enjoy. That’s why, when creating your animations, things like performance and accessibility make all the difference between an animation that delights and one that annoys or even hurts users.

也就是说,两种动画都是让人欣赏的。 这就是为什么在创建动画时, 性能可访问性之类的东西使令人愉悦的动画与烦扰甚至伤害用户的动画完全不同的原因。


Today CSS offers transitions and animations to add movement to the web. However, when it comes to animation on the web, JavaScript is still a big player. Why is this the case? At last we can run an animation using CSS alone, why on earth would anyone need JavaScript to do the job?

如今,CSS提供了过渡和动画功能,可以向网络添加移动效果。 但是,当涉及到网络动画时,JavaScript仍然扮演着重要角色。 为什么会这样呢? 最后,我们可以仅使用CSS来运行动画,为什么到底有人需要JavaScript来完成这项工作?

To help you decide between CSS and JavaScript animation, consider the following distinctions by Rachel Nabors.

为了帮助您在CSS和JavaScript动画之间做出选择,请考虑Rachel Nabors的以下区别 。

Animation can be:


  • static: the animation runs from the beginning through to the end without decision-making logic. CSS loaders are a case in point. You can create this kind of animation with CSS alone;

    静态的 :动画从头到尾一直运行,没有决策逻辑。 CSS加载器就是一个很好的例子。 您可以仅使用CSS来创建这种动画。

  • stateful: a sidebar that opens and closes at the click of a button is a common example of this type of animation. You can build this using CSS and a tiny bit of JavaScript to add and remove the CSS classes responsible for keeping track of the state of the element in your animation;

    有状态 :单击按钮即可打开和关闭的侧边栏是此类动画的常见示例。 您可以使用CSS和少量JavaScript进行构建,以添加和删除负责跟踪动画中元素状态CSS类。

  • dynamic: this kind of animation can have different outcomes, which depend on various factors like user interaction, DOM events, the state of the animation of other elements on the same document, etc. You can’t create dynamic animations with just CSS – in this context, JavaScript is most likely your best friend.

    动态的 :这种动画可能会有不同的结果,这取决于各种因素,例如用户交互,DOM事件,同一文档中其他元素的动画状态等。您不能仅使用CSS创建动态动画–在在这种情况下,JavaScript很可能是您最好的朋友。

Besides dynamic animations, you could turn to JavaScript for a helping hand with your animations if you come across any of the circumstances below:


  • you need to chain or stagger your animations on more than a few elements. In this case, each subsequent animation needs to occur after the previous one has completed. You can do this with CSS alone by coordinating the delay property on each animated element. However, if you need to change even just one value, making the necessary adjustments on all the chained elements can quickly become unmanageable;

    您需要在多个元素上链接或错开动画。 在这种情况下,每个后续动画都需要在前一个动画完成之后发生。 您可以通过在每个动画元素上协调delay属性来单独使用CSS来实现。 但是,如果您只需要更改一个值,则对所有链接的元素进行必要的调整可能很快就变得难以管理。

  • you are animating SVG graphics. In this case, the drawback is that CSS animation on SVG is not consistently supported across browsers;

    您正在为SVG图形制作动画。 在这种情况下,缺点是跨浏览器不能始终支持SVG上的CSS动画 。

  • if your project needs to support older browsers where CSS animation is not available, resorting to a robust JavaScript solution will make your animations more widely available.


If you’d like to read more on this topic, Myth Busting: CSS Animations vs. JavaScript by Jack Doyle, author of the Greensock Animation Platform, makes some good points.

如果您想了解更多有关此主题的内容, Greensock动画平台的作者Jack Doyle的Myth Busting:CSS动画与JavaScript 会给您一些好处。

新兴方案:Web动画API (An Up and Coming Alternative: the Web Animations API)

The W3C has been working on a specification that brings together CSS, SVG and JavaScript animation under a unified language without any need for external JavaScript libraries. The API is known as Web Animations and works great for the kind of dynamic animations for which CSS is less suited. You can read this helpful introduction to the Web Animations API (AAPI) by Dudley Storey here on your very own SitePoint.

W3C一直在研究一种规范,该规范以统一的语言将CSS,SVG和JavaScript动画组合在一起,而无需外部JavaScript库。 该API被称为Web动画 ,非常适合CSS不适合使用的动态动画。 您可以在自己的SitePoint上阅读Dudley Storey撰写的有关Web动画API (AAPI)的有用介绍 。

Work on the Web Animations API has been going on at a sustained pace and a polyfill is also available for browsers that don’t provide native support for the API.

Web Animations API的开发工作一直在持续进行,并且不提供对API的本机支持的浏览器也可以使用polyfill 。

All this sounds good and I actively encourage experimenting with the WAAPI. However, at the time of writing, browser support is sketchy and the specification might still change in the future. So, if the WAAPI is not a good fit for your project right now, you can turn to JavaScript animation libraries to get the job done.

所有这些听起来不错,我积极鼓励尝试使用WAAPI。 但是,在撰写本文时,对浏览器的支持是粗略的,将来该规范可能仍会更改。 因此,如果WAAPI目前不适合您的项目,则可以使用JavaScript动画库来完成工作。


There is a wide choice of JavaScript animation libraries for you to try out. At the time of writing GreenSock, also known as GSAP (GreenSock Animation Platform), and Velocity.js are among the big players.

您可以尝试多种JavaScript动画库。 在撰写本文时, GreenSock也被称为GSAP(GreenSock动画平台),而Velocity.js是其中的佼佼者。

Both are fantastic, user-friendly tools and I will talk about them in subsequent articles. However, I’d like to kick off this series with Anime.js, a new JavaScript animation library that’s been gaining some significant traction.

两者都是出色的,用户友好的工具,我将在后续文章中讨论它们。 但是,我想通过Anime.js (一个新JavaScript动画库)开始这个系列,该库已经获得了很大的关注。


The name Anime is Japanese for hand-drawn or computer animation (Japanese: アニメ)

动漫名称是日语,用于手绘计算机动画 (日语:アニメ)

anime.js 动画_用Anime.js动画化DOM

As for its features, Anime.js…


is a flexible yet lightweight JavaScript animation library. It works with CSS, Individual Transforms, SVG, DOM attributes and JS Objects.

是一个灵活而轻巧JavaScript动画库。 它与CSS,Individual Transforms,SVG,DOM属性和JS对象一起使用。

Anime.js supports the following browsers:


  • Chrome

  • Safari

  • Opera

  • Firefox

  • Internet Explorer 10+

    Internet Explorer 10+

有所有可用的动画库,为什么要使用动漫? (With All Animation Libraries Available, Why Anime?)

The answer to this question is best left to Anime’s author as he explains why he came up with Anime.js when there’s something as powerful as GSAP around:


GSAP can do a lot more than Anime. But it’s also way more heavy. My goal with this library was to keep the API simple as possible, focus on the things I really need (multiple timings, easings, playback controls…) while keeping the code super lightweight (9KB minified).

GSAP可以做的比动漫还多。 但这也更重。 我使用该库的目的是使API尽可能简单,专注于我真正需要的东西(多个定时,缓动,播放控件……),同时使代码保持超轻量(最小化9KB)。

Hacker News


In short, for dynamic animations of HTML and SVG elements which don’t require all of the features GSAP and other big libraries offer out of the box, Anime.js can be an excellent option for your project.



In what follows I have provided a few live samples to illustrate a basic use of Anime.js. Most animations will run a bit slowly for demonstration purposes.

接下来,我提供了一些实时示例来说明Anime.js的基本用法。 出于演示目的,大多数动画的运行速度会有些慢。

Including Anime.js is not different from including jQuery or any other familiar JavaScript library.


Download the .zip file from the library’s project’s page on GitHub, extract the files and add anime.min.js using <script> tags in your html document:


<script src="anime.min.js"></script>

Alternatively, you can use npm or bower:


npm install animejs
bower install animejs

向单个元素添加一个动画:弹跳球 (Adding One Animation to a Single Element: Bouncing Ball)

Once you’ve got Anime set up in your project, you can get started with the simplest kind of animation: just one element, a ball, bouncing up and down.


The first step is to call anime passing an object with a bunch of details about the animation. Here’s the basic structure:

第一步是调用anime传递带有大量有关动画细节的对象。 基本结构如下:

var bouncingBall = anime({

  //code here

Next, you need to flesh out the object above with some instructions on what to animate, the kind of animation, its duration, etc.


var bouncingBall = anime({
  targets: '.ball',
  translateY: '50vh',
  duration: 300,
  loop: true,
  direction: 'alternate',
  easing: 'easeInCubic'

The targets property tells Anime which element you want to animate. Here you can use a CSS selector like I did in the example above, or any of the following:

targets属性告诉动漫要动画的元素。 在这里,您可以像上面的示例一样使用CSS选择器,也可以使用以下任意一种:

  • DOM element, e.g., document.querySelector('.ball')


  • Nodelist, e.g., document.querySelectorAll('.ball')


  • JavaScript object, e.g., {elementName: 'ball'}

    JavaScript对象,例如{elementName: 'ball'}

  • JavaScript array, e.g., ['.ball']


If your targets property has more than one value, that is, you intend to apply your animation to more than one element, you can use an array as your data structure, like so:


var bouncingBall = anime({
  targets: ['.ball', '.kick'],
  //rest of the code

The second property in the example above moves the ball element vertically with translateY, which should be familiar to those using CSS. Tiffany Brown and others recommend using translate and scale to move elements and change their dimensions respectively, as opposed to targeting elements’ position properties or their width and height. This aids the performance and quality of the animation by avoiding browser reflows.

上面的示例中的第二个属性将球元素垂直移动了translateY ,这对于使用CSS的用户应该是熟悉的。 蒂法尼·布朗 ( Tiffany Brown)等人建议分别使用translatescale来移动元素并更改其尺寸,这与定位元素的位置属性或其宽度和高度相反。 通过避免浏览器重排,有助于动画的性能和质量。

Next in the list of properties in the above animation snippet is the duration property. This tells Anime how long you want the animation to last. If you have more than one animation taking place at different times, delay is another useful property.

上面的动画片段的属性列表中的下一个是duration属性。 告诉动漫您希望动画持续多长时间。 如果在不同时间发生多个动画,则delay是另一个有用的属性。

The loop property tells Anime how many times you want the animation to take place. Its default value is false, which makes the animation run just once. You can have your animation run indefinitely by changing this value to true, or have it run a precise number of times by setting this property to the desired number.

loop属性告诉Anime您希望动画进行多少次。 它的默认值为false ,使动画仅运行一次。 您可以通过将该值更改为true来无限期地运行动画,也可以通过将该属性设置为所需的数字来使动画运行精确的次数。

The direction property is also present in CSS animations and Anime allows you to set it to any of the values of its CSS counter-part: normal, reverse and alternate. This last value alternates between the normal direction of the animation and its reverse, which seems to work great for a bouncing ball.

direction属性也存在于CSS动画中,而Anime允许您将其设置为CSS对应部分的任何值: normalreversealternate 。 最后一个值在动画的法线方向和其反向之间交替,这似乎对弹跳球很有用。

Finally, the above code specifies an easing property for your animation. Is the rate of change constant? Perhaps the animation starts slowly and speeds up towards the end? Is there a bounce in the final part? The right easing value is a crucial ingredient of a polished and effective animation.

最后,以上代码为动画指定了easing属性。 变化率恒定吗? 也许动画开始缓慢并加速到结束? 最后部分有弹跳吗? 正确的宽松价值是优美而有效的动画的重要组成部分。

You can find out all the easing functions you can use with Anime with this simple snippet:



向弹跳球添加第二个动画 (Adding a Second Animation to the Bouncing Ball)

Let’s say you want the bouncing ball to get squashed a bit as it hits the bottom of its container. You can do this with Anime by adding specific animation parameters in the form of a JavaScript object. Using the bouncing ball example, here’s how you can achieve the desired effect:

假设您希望弹跳球在碰到容器底部时被压扁。 您可以使用Anime通过使用JavaScript对象的形式添加特定的动画参数来实现此目的。 以弹跳球为例,以下是实现所需效果的方法:

var bouncingBall = anime({
  targets: '.ball',
  translateY: '50vh',
  duration: 300,
  loop: true,
  direction: 'alternate',
  easing: 'easeInCubic',
  //new code
  scaleX: {
    value: 1.05,
    duration: 150,
    delay: 268

The code above adds a new property, scaleX, to increase the ball’s width and sets its value in the form of an object literal with specific keys that you can use to control your animation.

上面的代码添加了一个新属性scaleX ,以增加球的宽度,并以具有特定键的对象文字形式设置其值,您可以使用这些键来控制动画。

The value key lets you control the element’s width as you scale it on its horizontal axis, while the duration and delay keys let you set how long the animation is going to last and when it’s going to start with respect to the previous animation respectively.

value键可让您在元素的水平轴上缩放时控制元素的宽度,而duration delay键和delay键可让您分别设置动画要持续多长时间和何时相对于上一个动画开始。

See the Pen Bouncing Ball with Anime JS by SitePoint (@SitePoint) on CodePen.

请参阅CodePen上的SitePoint ( @SitePoint ) 使用Anime JS的笔弹跳球 。

If you inspect the code using you favorite browser’s dev tools, you’ll see how Anime animates the element by injecting an inline <style> tag and dynamically updating the values of the CSS transform property:

如果使用您喜欢的浏览器的开发工具检查代码,您将看到Anime如何通过注入内联<style>标签并动态更新CSS transform属性的值来使元素动画化:

anime.js 动画_用Anime.js动画化DOM

连续动画两个元素:踢球 (Animating Two Elements in Succession: Kicking a Ball)

The sample code below shows one way in which you can animate two elements, in this case two images, in succession: the second animation starts once the first animation has completed.


var kickBall = anime({
  targets: '.kick',
  scale: 1.2,
  duration: 300,
  easing: 'easeInCubic',
  complete: function() {
      targets: '.ball',
      translateX: '70vw',
      scale: 1.5,
      easing: 'easeOutBounce',
      delay: 150

The ball animates only after it has been kicked. With Anime.js you can stagger the animations using the complete() method, which in this case contains a second object with instructions to animate the ball element.

球只有在被踢过后才会动画。 使用Anime.js,您可以使用complete()方法使动画交错,在这种情况下,该方法包含第二个对象,该对象带有对ball元素进行动画处理的指令。

See the Pen Animate Two Elements with Anime JS by SitePoint (@SitePoint) on CodePen.

请参阅CodePen上的SitePoint ( @SitePoint )的Pen 用Anime JS对两个元素进行动画 处理 。

Image courtesy of


Of course, it takes a few keyframes and a fancy cubic bezier function to quickly approximate this kind of static animation in CSS. In this case, you won’t need any JavaScript at all and will end up with a smooth animation that runs natively in the browser.

当然,需要一些关键帧和精美的三次方贝塞尔函数才能快速近似CSS中的这种静态动画。 在这种情况下,您根本不需要任何JavaScript,并且最终将获得在浏览器中本地运行的平滑动画。

Here’s the CSS-only demo:


See the Pen Animating Two Images with CSS by SitePoint (@SitePoint) on CodePen.

见笔与CSS动画效果两张图片由SitePoint( @SitePoint上) CodePen 。

播放,暂停和重新启动动画 (Playing, Pausing and Restarting an Animation)

Anime.js lets you control when to play, stop and restart your animations with the .play(), .pause(), and .restart() methods. You can also find a specific point along the course of your animation with the .seek() method.

通过Anime.js,您可以使用.play() .pause().restart()方法控制何时播放,停止和重新启动动画。 您还可以使用.seek()方法在动画过程中找到特定点。

For instance, here’s how you can control the kicking ball animation with the play button.


//Animating the kick
var kickBall = anime({
  targets: '.kick',
  scale: 1.2,
  duration: 300,
  delay: 100,
  easing: 'easeInCubic',
  autoplay: false

//Animating the ball
var movingBall = anime({
  targets: '.ball',
  translateX: '70vw',
  scale: 1.5,
  easing: 'easeOutBounce',
  delay: kickBall.duration + 100,
  autoplay: false

/* Playing the animation 
when clicking the play button */
btnPlay.addEventListener('click', function(e) {

A few things to note about the snippet above:


  • to be able to control both the kick and the ball using a button, I created two separate objects. I could have nested the animation of the ball inside that of the kick, but my experience has been that the button could only control the main animation, i.e., the kick, not the nested one;

    为了能够使用按钮控制踢球和控球,我创建了两个单独的对象。 我本可以将球的动画嵌套在踢的动画中,但是我的经验是按钮只能控制主要动画,即踢,而不是嵌套的动画。
  • to prevent your animations from running on page load, it is necessary to set autoplay to false;


  • finally, it’s just a matter of calling the .play() method on the kickBall and movingBall objects to have them behave exactly as you want.


See the Pen Anime JS with Buttons by SitePoint (@SitePoint) on CodePen.

请参阅CodePen上的SitePoint ( @SitePoint )的带有按钮的Pen Anime JS 。

Although replicating the behavior of the play and pause buttons is quickly done using the CSS animation-play-state property and a tiny bit of JavaScript, the same does not hold if you want to restart your animation once it’s finished running or retrace an exact point along its course.

尽管可以使用CSS animation-play-state属性和少量JavaScript快速完成播放按钮和暂停按钮的行为复制,但是如果您希望动画一旦完成运行或重新定位精确点就重新启动动画,则该操作将不起作用一路走来。

使用Anime.js动画化内联SVG属性 (Animating Inline SVG Attributes With Anime.js)

This last demo illustrates how you can animate attributes of an inline SVG graphic, in this case the graphic represents a cute cat playing with a ball.


The demo uses CSS classes on the various paths and shapes that make up the SVG graphic, so that it’s easy to target them in the code.


This is how you can animate the cat’s eyes:


var movingEyes = anime({
  targets: ['.inner-left-eye', '.inner-right-eye'],
  cy: 400,
  duration: 500,
  delay: function(el, index) {
    var singleDelay = index === 0 ? 300 : index * 500;
    return singleDelay;
  autoplay: false

The code above lowers the cat’s eyes by modifying the value of the cy attribute of the circle shapes that make up the cat’s pupils.


If you notice, the eyes move in succession. I’ve done this on purpose to show you one more cool way in which you can stagger animations with Anime.js. The delay property can be a number but also a function. When you use a function as in the code above, you have programmatic control over the starting time of your animation. The function tells Anime that if the element you want to animate is the first one (at the 0 position in the targets array), i.e., the left eye, then the animation has a 300ms’ delay, otherwise the element has a delay that results from the index number (i.e., 1) multiplied by 500ms with respect to the completion of the previous animation.

如果您注意到,眼睛会连续移动。 我这样做是为了向您展示一种更酷的方式,您可以在其中使用Anime.js交错动画。 delay属性可以是数字,也可以是函数。 当您使用上面代码中的函数时,您可以对动画的开始时间进行编程控制。 该函数告诉动漫,如果要设置动画的元素是第一个元素(位于targets数组的0位置),即左眼,则动画具有300ms的延迟,否则该元素具有导致的延迟相对于先前动画的完成,将索引号(即1)乘以500ms。

See the Pen Anime JS SVG Example by SitePoint (@SitePoint) on CodePen.

请参阅CodePen上SitePoint ( @SitePoint )的Pen Anime JS SVG示例 。

SVG graphic adapted from original on



I opened this article with a brief look at how animation is used on the web, followed by a discussion on when you could consider JavaScript versus CSS for animation, and a cursory reference to the Web Animations API.


I also introduced Anime.js, the first animation library in this series, by illustrating some of its features and putting it to work on CodePen.


Overall, I’ve found Anime.js fun to work with: its features cover a fair number of use cases, its syntax is quite straightforward, and it lets you create smooth, beautiful animation effects.


For those who first approach it, I must say the file on GitHub is the only documentation available at this point.


That said, you can find some great answers to some of your questions in the project’s GitHub issues section, which seems to be closely monitored by Anime’s creator Julian Garnier.

就是说,您可以在该项目的GitHub问题部分中找到一些问题的好答案,该部分似乎受到Anime的创建者Julian Garnier的密切监视。

Also, you can learn more on how to use the library by digging into the code of some of the amazing demos that use Anime as their animation engine:


  • Anime.js Homepage


  • Demos and examples on CodePen


  • demo: Inspiration for Letter Effects


  • Demo: Background Segment Effect


  • Demo: Fancy SVG Letter Animation


  • Demo: Multi-Layout Slideshow


  • Demo: Item Reveal Animations with SVG


If you have used Anime.js and would like to share your experience or would like to suggest your favorite animation library for this series, hit the comment box below with your message.



anime.js 动画

anime.js 动画_用Anime.js动画化DOM相关教程

  1. 使用Tumult Hype进行Web动画的高级定时和缓动
  2. JQuery动画控制元素
  3. Activity过渡动画
  4. css 音频动画_将CSS动画与HTML5音频同步
  5. 安卓scale动画pivotX详解
  6. SpriteKit小球被旋涡吞噬动画的进一步改进
  7. Unity3DUnity5.6的Mecanim Animator动画系统结合MMD4Mecanim插件
  8. 放yy直播点赞动画