Comparison of animation using CSS and JavaScript. Promising JavaScript libraries and plugins for animation

A small library for creating animations on JavaScript based. It can be used to animate CSS properties, SVG images, or DOM tree attributes on a web page. The library allows you to control all aspects of animation and provides many ways to designate elements that need to be set in motion.

You have complete control over the order in which the animation plays and control how the animations of different elements are synchronized relative to each other. The library supports everything modern browsers, including IE10 and later.

In this series of tutorials, you will learn about all the features of Anime.js and will be able to use the library in your projects.

Note If you are completely new to JavaScript, we suggest you familiarize yourself with this programming language.

Installing the library

To install, you can use npm or bower commands:

Npm install animejs bower install animejs

You can also download the library and include or link to it in your project latest version via CDN.

After successful installation, you will be able to use Anime.js to add interesting animations to your elements. Let's start with basic capabilities libraries.

Defining Target Elements

To create an animation using Anime.js, you call the anime() function and pass it an object with key-value pairs that define the target elements and properties you want to animate. You can use the targets keyword to let the library know what you need to animate. This keyword can take a value in different formats.

CSS selectors: you can pass one or more selectors as values ​​for keyword targets.

Var blue = anime(( targets: ".blue", translateY: 200 )); var redBlue = anime(( targets: ".red, .blue", translateY: 200 )); var even = anime(( targets: ".square:nth-child(even)", translateY: 200 )); var notRed = anime(( targets: ".square:not(.red)", translateY: 200 ));

In the first case, Anime.js will animate all elements with the blue class. In the second - blue or red. In the third case, Anime.js will animate all child even elements with the square class. And in the latter case, the library will interact with all elements with the square class that do not have the red class.

DOM nodes or NodeList: You can also use a DOM node or NodeList as the value for the targets keyword. Look at an example of using a DOM node for targets.

Var special = anime(( targets: document.getElementById("special"), translateY: 200 )); var blue = anime(( targets: document.querySelector(".blue"), translateY: 200 )); var redBlue = anime(( targets: document.querySelectorAll(".red, .blue"), translateY: 200 )); var even = anime(( targets: document.querySelectorAll(".square:nth-child(even)"), translateY: 200 )); var notRed = anime(( targets: document.querySelectorAll(".square:not(.red)"), translateY: 200 ));

In the first case, the getElementById() function was used to access specific element. The querySelector() function was used to access an element with class blue . And the querySelectorAll() function was used to access all elements within the document that match a group of specific selectors or, conversely, are not included in it.

There are many functions that you can also use to select the target element. For example, you can access elements with a specific class using the getElementsByClassName() function. Or to elements with a specific tag using the getElementsByTagName() function.

Any function that returns a DOM node or NodeList can be used to set the value of targets in Anime.js.

Object: you can use JavaScript objects as the value for targets . The key of this object is used as the identifier, and the value is used as the number to animate.

You can then show the animation inside another HTML element using additional JavaScript code. Below is an example of animating the values ​​of two different keys one object.

Var filesScanned = ( count: 0, infected: 0 ); var scanning = anime(( targets: filesScanned, count: 1000, infected: 8, round: 1, update: function() ( var scanCount = document.querySelector(".scan-count"); scanCount.innerHTML = filesScanned.count ; var infectedCount = document.querySelector(".infected-count"); infectedCount.innerHTML = filesScanned.infected;

The code above will drive the scanned file counter from 0 to 1,000 and the infected file counter from 0 to 8. Remember that you can animate numeric values only this way. If you try to animate a key from AAA to BOY, an error message will be displayed.

In addition, the code used the function callback update key, which is called every frame during the animation. Here it was used to update the number of scanned and infected files. However, you can go further and show users an error message when the number of infected files exceeds a certain threshold.

Array: ability to specify JavaScript array targets will be useful if you need to animate a lot of elements that relate to different categories. For example, if you want to animate a DOM node, an object, and a variety of other elements based on CSS selectors, you can do this by putting them in an array, and then defining the array as the value for targets . The example below should make things clearer.

Var multipleAnimations = anime(( targets: , translateY: 250 ));

What properties can be animated using Anime.js

Now you know how to identify the different elements that need to be animated. It's time to find out which properties and attributes can be animated using the library.

CSS Properties

These include, for example, width, height, and color for different target elements. The final values ​​of various animated properties like background-color are determined using lowerCamelCase. Thus background-color becomes backgroundColor . The code below illustrates animating the position of the left object and the background color (backgroundColor) of the target object.

Var animateLeft = anime(( targets: ".square", left: "50%" )); var animateBackground = anime(( targets: ".square", backgroundColor: "#f96" ));

Properties can take different types the values ​​they would take using regular CSS. For example, the left property could have the following values: 50vh , 500px or 25em . You can also omit the unit of measurement after the number, but in this case it will become px by default. Similar actions can be done with background-color , specifying the color as hexadecimal value or using RGB or HSL code.

CSS Transformation

Transformation along the X and Y axes is achieved using the translateX and translateY properties. Similarly, you can scale, skew, or rotate an element along a specific axis using the scale, skew, or rotate properties appropriate to that specific axis.

It is possible to define different angles either in degrees or using the turn property. A turn value of 1 corresponds to 360 degrees. This makes calculations easier because you know how much to rotate the elements relative to their axis. The example below shows how to animate scaling, transition, or rotation of a single property or all of them at once.

Var animateScaling = anime(( targets: ".square", scale: 0.8 )); var animateTranslation = anime(( targets: ".square", translateX: window.innerWidth*0.8 )); var animateRotation = anime(( targets: ".square", rotate: "1turn" )); var animateAll = anime(( targets: ".square", scale: 0.8, translateX: window.innerWidth*0.8, rotate: "1turn" ));

SVG Attributes

The only condition is that the attribute value must be numeric. The ability to animate different attributes opens up the possibility of creating some cool effects. Since this article is for informational purposes only, it will contain simple examples.

Abstract: A simple example: the extinction method yellow color. Animation using JavaScript libraries. More complex example: Move and resize. CSS transitions.

The principle behind fading is that the background color of the fading element is set to yellow, and then, through a series of steps, its color returns to its original color. So if the original background color was red, then the color is then set to yellow, then orange-yellow, then orange, then red-orange, and then red. The number of steps used determines how smoothly the color change occurs, and the time between steps determines how long the color change continues. When changing color you can use useful fact from CSS: a color can be defined as a triple of regular numbers or as a hexadecimal string. Therefore #FF0000 (red color) can also be defined as rgb(255,0,0) . Changing from yellow to red in five steps means, therefore, going from rgb(255,255,0) (yellow) to rgb(255,0,0) in the following five steps:

rgb(255,255,0) rgb(255,192,0) rgb(255,128,0) rgb(255,64,0) rgb(255,0,0)

More complex example: moving and resizing

Although the yellow fading method demonstrates animation, it is somewhat boring. When most people think of animation, they usually think of movement. An interesting technique for alerting the user that something has happened without interrupting their workflow is to use a modeless message. Instead of displaying a dialog alert windows() that requires the user to click OK before they can continue, place the message simply in a floating div on the page that unobtrusively stays there until it receives confirmation. The second one is enough interesting thing this could then be to allow the user to return to a message for which they have confirmed they wish to read it again. So let's implement a floating message that, when clicked, collapses to the corner of the screen and can then be restored again when clicked. You can watch a short demo of this "collapsing message" (http://dev.opera.com/articles/view/javascript-animation/moving_messages_jq.html) to get the general idea.

If you're doing some serious animation work, or some serious JavaScript work, it's almost always worth using JavaScript library. This will allow you to create the desired presentation for users without having to worry about the mathematical intricacies required to perform the animation. (Having seen the first example above, you now know how to do mathematical calculations and how to use setInterval but you will save time and own strength using ready-made solutions.)

The above demo uses to work jQuery library(http://jquery.com/), but as mentioned, most libraries provide a similar enough animation concept that you should be able to implement the principle part using your preferred library. Essentially, you need to do the following:

  • Show a floating message in the center of the screen
  • When it is clicked:
  • Move its horizontal position to the far right position
  • Move its vertical position up
  • Set its width to 20px
  • Set its height to 20px
  • Make its density equal to 20%, so that it becomes almost transparent and hide the text in it
  • When this "mini" version of the message is clicked, restore it to the center of the screen (i.e., the opposite of what we did to compress it) and so that the user gets a clear picture of what happened to their message, jumping from the full size The messages to the mini-message should be animated (so they can see the message "shrink" into the corner of the window).
  • Perform animation with using jQuery very easy: just use the . animate() and provide the desired final result animation (and how long it should run):

    $(ourObject).animate(( width: "20px", height: "20px", top: "20px", right: "20px", marginRight: "0px", opacity: "0.2" ), 300);

    The function takes ourObject and, in 300 milliseconds, replaces its width and height with 20px, its top and right positions with 20px, its margin-right style property with 0px, and its density (in browsers that support image density) with 20%. Then it's just a matter of programming in style

    Paul is a Design and Perf Advocate

    Evangelises Chrome and the mobile web in the Developer Relations team at Google.

    There are two main ways to create animation on the Internet: with using CSS and JavaScript. Which one should you choose? This depends on other characteristics of your project, as well as what effects you are trying to achieve

    TL;DR
    • Use Animation using CSS for simple, short transitions such as switching the state of elements user interface.
    • Use JavaScript animation when you need complex effects such as bouncing, stopping, pausing, rewinding, or slowing down.
    • If you choose to animate using JavaScript, use TweenMax or, if you want a simpler solution, TweenLite.

    Most simple animation can be created using both CSS and using JavaScript, however, the amount of labor and time spent will vary (see also article). Each option has its own advantages and disadvantages, but there are good rules to follow:

    • Use CSS when working with small, self-contained states of UI elements. CSS transitions and animations are ideal for displaying a navigation menu on the side of the screen or displaying a tooltip. JavaScript can be used to control the state, but the animation itself will be done using CSS.
    • Use JavaScript when you need a high degree of control over your animation. When you need to implement dynamic touch position tracking or an animation that needs to be stopped, paused, slowed down, or started in reverse direction, you should use JavaScript.

    If you're already using jQuery or a JavaScript framework that has animation functionality, you may be more comfortable using those features rather than switching to CSS.

    Animation with CSS

    Animation with CSS is without a doubt the most in a simple way make something move on the screen.

    The following is the CSS code that moves an element 100 pixels along the X and Y axes. This is done using CSS transitions, which are set to run within 500 ms. When you add the move class, the value of the transform property changes and the transition begins.

    Box ( -webkit-transform: translate(0, 0); -webkit-transition: -webkit-transform 500ms; transform: translate(0, 0); transition: transform 500ms; ) .box.move ( -webkit-transform: translate(100px, 100px); transform: translate(100px, 100px )

    If, as in the snippet above, you create separate CSS classes to control the animation, you can turn each animation on and off using JavaScript:

    Box.classList.add("move");

    This will allow your applications to be very well balanced. The focus can be on managing state using JavaScript. Otherwise, you just need to set the appropriate classes for the target elements, and the animation will be performed by the browser. If you choose this path, you can receive transitionend events for the element. However it is not suitable for old Internet versions Explorer; version 10 was the first to support these events. All other browsers have supported this event for quite some time.

    The JavaScript code required to receive the transition end event is as follows:

    Var box = document.querySelector(".box"); box.addEventListener("transitionend", onTransitionEnd, false); function onTransitionEnd() ( // Handle the transition finishing. )

    Besides using CSS transitions, you can also use CSS animation, which allows much more precise control over individual keyframes, durations, and animation passes.

    Note: If animation is new to you, you should know that keyframes are an old term used from the days when animation was drawn by hand. Animators created special frames for a piece of action called key frames. They captured things like the outermost part of some movement, and then drew all the individual frames between the keyframes. Today, when creating animations with CSS, there is a similar process where we tell the browser what values ​​it should have. CSS properties at certain points, and the browser fills in the gaps.

    For example, you can animate a square using transitions in the same way, but the animation will take place without any user action (for example, clicking) and will repeat endlessly. In addition, you can change multiple properties at the same time:

    /** * This is a simplified version without * vendor prefixes. With them included * (which you will need) things get far * more verbose! */ .box ( /* Choose the animation */ animation-name: movingBox; /* The animation's duration */ animation-duration: 1300ms; /* The number of times we want the animation to run */ animation-iteration-count : infinite; /* Causes the animation to reverse on every odd iteration */ animation-direction: alternate; @keyframes movingBox ( 0% ( transform: translate(0, 0); opacity: 0.3; ) 25% ( opacity: 0.9 ; ) 50% ( transform: translate(100px, 100px); opacity: 0.2; ) 100% ( transform: translate(30px, 30px); opacity: 0.8; ) )

    When creating an animation using CSS, you define the animation itself independently of the target element, and then select the desired animation using the animation-name property.

    Animation with CSS is still very browser-specific, with the prefix -webkit- being used to denote it in Chrome, Safari, Opera, Safari Mobile, and Android Browser. IN Internet Explorer and Firefox prefixes are not used. There are many tools that allow you to create the required CSS versions with prefixes, while a version without a prefix can be written in the source files.

    Animation with JavaScript

    Creating animations with JavaScript is more difficult than writing transitions or animations with CSS, but JavaScript generally gives the developer much more ample opportunities. Typically you use the requestAnimationFrame function and then manually determine the value of each property of the element being animated on each frame of the animation.

    Note: On the Internet you can find publications of code in which the setInterval or setTimeout function is used for animation. This is a terrible solution because the animation will not be synchronized with the screen frequency and therefore there is a very high chance of jitter and dropouts. It is not advisable to use such code in any situation, and instead it is recommended to use the requestAnimationFrame function, which is synchronized appropriately.

    Function Box () ( var animationStartTime = 0; var animationDuration = 500; var target = document.querySelector(".box"); this.startAnimation = function() ( animationStartTime = Date.now(); requestAnimationFrame(update); ) ; function update() ( var currentTime = Date.now(); var positionInAnimation = (currentTime - animationStartTime) / animationDuration; var xPosition = positionInAnimation * 100; var yPosition = positionInAnimation * 100; target.style.transform = "translate(" + xPosition + "px, " + yPosition + "px)"; if (positionInAnimation 1000 / 50 = 20ms var timer = setInterval(function())( // decrease the current opacity value op -= d0; // set opacity to the DOM element elem .style.opacity = op; // reduce the number of remaining animation steps steps--; // if the animation is finished if(steps