Comparison of animation using CSS and JavaScript. CSS3 animations and the new javascript Animate() method

The final part will describe the various callback functions used to perform functions depending on the progress of the animation. Almost every example in previous articles used CSS properties to show how they work various methods and parameters. You might be under the impression that Anime.js is more suitable for animating CSS properties. In this tutorial you will learn that it can also be used to animate SVG files.

In the three previous articles, we examined many of the functions of the Anime.js library. You can learn how to select target elements; about the types of parameters that are used to control the delay and duration of the animation; c - how to have more control over the values ​​of single properties.

Callback functions

Callbacks are used to perform functions based on the progress of the animation. There are 4 functions in Anime.js callback: begin , run , update and complete . Each of them runs in certain time and takes an animation object as its argument.

The begin() function is called when the animation begins. This means that if the animation has a delay parameter with a value of 800 milliseconds, then begin() will not be called until 800 milliseconds later. You can check whether an animation has started or not using the animationName.begin function, which returns true (started) or false (did not start).

Run is used to execute a function every frame after the animation starts. If you need to execute a function every frame from the very beginning of the animation, regardless of the delay parameter, then use the update callback function.

The complete callback function is similar to begin , only it is called after the end. To check whether the animation has completed or not, use animationName.complete , just like with begin .

We used the update callback function back in the day to update the number of scanned and infected files. In this article we will expand on the scanning example and you will see how all the callback functions work.

Var filesScanned = ( count: 0, infected: 0 ); var scanCount = document.querySelector(".scan-count"); var infected = document.querySelector(".infected-count"); var scanning = anime(( targets: filesScanned, autoplay: false, count: 100, infected: 8, delay: 1000, duration: 2000, easing: "linear", round: 1, update: function(anim) ( if (anim .currentTime< 1000) { document.querySelector(".update-cb").innerHTML = "Creating an Index..."; } }, begin: function() { document.querySelector(".begin-cb").innerHTML = "Starting the Scan..."; }, run: function() { scanCount.innerHTML = filesScanned.count; infected.innerHTML = filesScanned.infected; }, complete: function() { document.querySelector(".complete-cb").innerHTML = "Scan Complete..."; } });

In the example above, we intentionally added an animation delay so that we could see differences in the execution time of different callback functions. The update callback function starts executing immediately after the animation object is created.

The animation itself begins with a delay of 1000 milliseconds, and it is at this moment that the begin function fires, which shows the user the message “Starting the Scan...”. At the same time run starts executing and updating numeric values object after each frame. After the animation finishes, the complete callback displays the message “Scan Complete...”.

Smoothness functions

Smoothness functions are used to control transition initial value properties into the final. These functions can be defined using the easing parameter, which can take values ​​either as strings or as custom Bezier curve coordinates (as an array).

There are 31 built-in smoothing functions. One of them is called linear , the other 30 consist of different variations of easeIn , easeOut and easeInOut . The elastic class defines three smoothness functions: easeInElastic, easeOutElastic, and easeInOutElastic. You can control them using the elasticity parameter. The value of this parameter can only be in the range from 0 to 1000.

Using easeIn makes the value change faster, starting from zero. This means that it will change slowly at first, and quickly in the end. The rate of change is zero at the beginning and 1000 at the end.

The easeOut function slows down the change in value starting from the maximum speed.

easeInOut increases the speed at which values ​​change at the beginning and slows them down at the end. This means that in the middle of the animation the speed will be the fastest. The following box shows the difference between these smoothness functions:

You can create your own easing features using anime.easings. Below is an example of creating custom functions smoothness:

Anime.easings["tanCube"] = function(t) ( return Math.pow(Math.tan(t * Math.PI / 4), 3); ) anime.easings["tanSqr"] = function(t) ( return Math.pow(Math.tan(t * Math.PI / 4), 2 ) var tanCubeSequence = anime(( targets: ".tan-cube", translateX: "75vw", duration: 2000, easing: " tanCube", autoplay: false )); var tanSqrSequence = anime(( targets: ".tan-sqr", translateX: "75vw", duration: 2000, easing: "tanSqr", autoplay: false ));

Animations based on SVG files

In all motion-related animations that have been created up to this point, the target elements have moved in a straight line. In Anime.js you can move elements along complex SVG paths with big amount curves with the ability to control the position and angle of animated elements on the contour. To move an element along the X axis on a path, use path("x") . Similarly, elements can be moved along the Y axis using path("y") .

If the contour is not represented as a straight line, then it will almost always form an angle relative to the main horizontal line. When rotating any non-circular animation element, the overall picture will look more natural if the element moves along the corner of the path. This can be done by setting the rotate property to path("angle") . Below is a code example that animates four elements with different meanings smoothness along the SVG contour:

Var path = anime.path("path"); var easings = ["linear", "easeInCubic", "easeOutCubic", "easeInOutCubic"]; var motionPath = anime(( targets: ".square", translateX: path("x"), translateY: path("y"), rotate: path("angle"), easing: function (el, i) ( return easings[i]), duration: 10000, loop: true ));

In the inset below, you can see that the red square with the easeInCubic function moves the slowest at the beginning, but the fastest at the end. The situation is similar in the case of the orange square - it moves fastest at the beginning, but slowest at the end.

It is possible to animate the transformations of different SVG shapes from one to another using Anime.js. The only condition for transforming shapes is to have an equal number of anchor points. This means that triangles can only be converted into other triangles, quadrilaterals into quadrilaterals, and so on. Trying to transform elements with an unequal number of anchor points will result in a drastic change in shape. Below is an example of triangle transformations:

Var morphing = anime(( targets: "polygon", points: [ ( value: "143 31 21 196 286 223" ), ( value: "243 31 21 196 286 223" ), ( value: "243 31 121 196 286 223" ), ( value: "243 31 121 196 386 223" ), ( value: "543 31 121 196 386 223" ) ], easing: "linear", duration: 4000, direction: "alternate", loop: true ));

One of the most interesting effects Anime.js is the ability to create line drawings. All you have to do is provide the library with the outline you want to use for the line drawing; provide other parameters by which duration, delay, and smoothness are controlled. The example below used the complete callback to make the fill of the Font Awesome anchor graphic yellow.

Var lineDrawing = anime(( targets: "path", strokeDashoffset: , easing: "easeInOutCubic", duration: 4000, complete: function(anim) ( document.querySelector("path").setAttribute("fill", "yellow" ); ) ));

Using knowledge of all the concepts you have learned, you will be able to create more complex line drawings with much more better control over how they are drawn. Below is an example of rendering a name using SVG:

Var letterTime = 2000; var lineDrawing = anime(( targets: "path", strokeDashoffset: , easing: "easeInOutCubic", duration: letterTime, delay: function(el, i) ( return letterTime * i; ), begin: function(anim) ( var letters = document.querySelectorAll("path"), i; for (i = 0; i< letters.length; ++i) { letters[i].setAttribute("stroke", "black"); letters[i].setAttribute("fill", "none"); } }, update: function(anim) { if (anim.currentTime >= letterTime) ( document.querySelector(".letter-m").setAttribute("fill", "#e91e63"); ) if (anim.currentTime >= 2 * letterTime) ( document.querySelector(".letter-o ").setAttribute("fill", "#3F51B5"); ) if (anim.currentTime >= 3 * letterTime) ( document.querySelector(".letter-n").setAttribute("fill", "#8BC34A" ); ) if (anim.currentTime >= 4 * letterTime) ( document.querySelector(".letter-t").setAttribute("fill", "#FF5722"); ) if (anim.currentTime >= 5 * letterTime ) ( document.querySelector(".letter-y").setAttribute("fill", "#795548"); ) ), autoplay: false ));

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:

, 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:

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

Note:. 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.

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)";<= 1) requestAnimationFrame(update); } } var box = new Box(); box.startAnimation();

This code becomes very complex and difficult to manage if you try to cover multiple cases, so in general it is recommended to choose one of the many JavaScript animation libraries available. If you're already using jQuery in your project, then you probably shouldn't switch to other options. Use the .animate() functions. If you need a specialized library, try Greensock's exceptionally powerful TweenMax. There is a simplified version called TweenLite that produces smaller files.

Because JavaScript animation allows you to have complete control over the styles of elements at each step, you can slow down, pause, stop, play in reverse, and do other manipulations with the animation.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. For details, see ours. Java is a registered trademark of Oracle and/or its affiliates.

Updated August 8, 2018

This material is devoted to animation on HTML pages, animation performance, prospects for use, as well as animation in HTML5 mobile applications and games.

Javascript animation

First of all, let's start by looking at JS animation on an HTML page. Animation in JavaScript can be carried out either with setInterval, with which you can set static frames per second, or using a regular function that at the end calls itself or with window.requestAnimationFrame.

Here is the simplest logic for how animation works in JS:

var el=document.getElementById("elem");
mar=10; //static initial data
//the cycle begins
mar=mar+1;
el.style.marginLeft=mar+"px";
//loop ends

The beauty of JS is that you can conveniently extend the native tools and use, for example, jQuery animation or use Velocity. This significantly speeds up productivity. However, in particular, Velocity does not use JS for animation, but the animation itself is performed there in CSS, which will be discussed below.

SVG animation

We can't help but mention SVG animation. It itself is very good, but it does not work in mobile browsers. Or rather, only SMIL works on Android 3.0-higher. As unpleasant as it may be to say, SVG itself works in the WebView method, but everything related to animation in this tag, alas...

Wherever she works, she shows good performance. See for yourself.


style="stroke:#ff0000; fill: #0000ff">
attributeName="transform"
begin="0s"
dur="10s"
type="rotate"
from="0 60 60"
to="360 60 60"
repeatCount="indefinite"
/>

A distinctive feature is that there are no pixels inside SVG, but rather some abstract values. Once you specify the height and width of the svg element, you can specify a viewbox attribute, with which you can adjust the position of the inner elements and their relative size. SVG can be made to any length and width and it will adjust the internal objects to fit the size of the viewbox.

Canvas animation

This type of animation is very common in browsers on regular computers, particularly when creating games. The disadvantages are:

1. Lack of DOM identification for elements.

2. The higher the resolution, the lower the performance.

In mobile browsers, canvas animation does not work smoothly.

CSS Animation

Let's look at animation using CSS3. As you know, in CSS3 we came to an amazing animation property with which you can fully animate certain objects.

How does this happen? For example, we want to move the #obj element to the right by 300 pixels and move it back, looping the animation indefinitely. With CSS3 this has become a very easy operation.

In addition to the standard width and height, we assign the following properties to the object:

Webkit-animation: 3s moving linear infinite;
animation: 3s moving linear infinite;

For greater cross-browser compatibility, we set two properties for the object, in which 3s - 3 seconds to complete the entire animation, moving - the name of the animation that is applied to the object (more details below), linear - a flag that makes the object move at the same speed in all areas, infinite - flag that makes the animation endless.

Well, now let's touch on the moving animation itself. It will need to be written in the same CSS file where you apply it. Previously, and even now, some people use the left/right/top/bottom or margin parameters to move an object across the screen. This is actually quite bad practice and shouldn't be done as it's a bit unoptimized - you can achieve smoother movement with other CSS3 properties. These properties are translatex and translatey.

/*Bad animation*/
@-webkit-keyframes moving (
from (margin-left: 0;)
50% (margin-left: 300px;)
to (margin-left: 0;)
}

/*Good animation*/
@-webkit-keyframes moving (
from (transform: translatex(0);)
50% (transform: translatex(300px);)
to (transform: translatex(0);)
}

It should also be noted that transition in events such as hover also behaves very well on mobile devices. Well, in general, you can attach the same transition or CSS3 animation to any element using JS. In this case, you will get the best option (JS specifies what to animate, CSS animates).

Since this is the case, when creating games they usually use frameworks and tools that facilitate development. One of these is Sencha Animator, which allows you to do various things using CSS and has a user-friendly interface.

What is better and faster: CSS animation or JS animation?

First, we can go a little deeper into the computational part to clarify the situation a little. Javascript is an interpreted language and in order to execute it, the browser's JS engine has to constantly parse the instruction (code) during execution and then convert it into machine-readable code. The situation with CSS is slightly different. The fact is that it is immediately compiled into machine language and thus shows better performance in animation.

CSS animation by default is an order of magnitude more productive than Javascript, but there are some nuances when using JS gives a greater performance advantage.

As was said in the latest proposals about CSS animation, it is better to use CSS for processing animation, and JS to indicate what to process (simply by hanging, for example, on a class element with the necessary prescribed animations).

It was a question of performance, the next question was relevance. Despite all the seemingly advantageous aspects of CSS, situations arise that it is better to use JS. It happens.

Optimizing Animation Performance

If you are making an HTML 5 application on Android, you can try the following:

Add android:hardwareAccelerated="true" to your activity parameters

This will give acceleration on hardware, the GPU, with this option enabled, will rush into work and, along with the CPU, will be completely busy processing your application. The only downside is that the battery life will be a little more fun.

Also, do not use the onclick event (even though it works on the touchscreen). The fact is that this event causes a delay of about a third of a second, and to avoid this, it is better to use ontouchstart and ontouchend.

Be sure to add and write in the comments what was not mentioned in the article. Together we will create high-quality material in Russian.

07.02.2016
If you are now in a situation where you need to create an impressive animation for a website, then this post will definitely give you useful tools.

Hello friends! In this article, I invite you to check out my selection of great CSS libraries and JS plugins that will help you implement the most compatible animations on your site in minutes.

JavaScript plugins for animation

If you want to create animations that are triggered by some event or action, then JavaScript animation plugins will greatly help you with this. But it's worth noting that most of these animations are written in CSS3 and controlled using JavaScript.

AniJS

Dynamics.js

Dynamic.js is a JavaScript library for creating physics-based animations.

mo.js

mo.js is an excellent library for creating motion graphics. You often saw an example of such graphics when Google posted a new thematic logo (doodle), which animated when hovered or clicked.

cta.js

cta.js - JavaScript plugin for creating animated calls to action. Many of them look very impressive.

animo.js

animo.js is a powerful tool for managing CSS3 animations.

html5tooltips.js

html5tooltips.js - good old tooltips with modern design and animation without dependencies, connect and use.

Rocket

Rocket is an interesting JS library that allows you to animate an element's path to a target.

scrollReveal.js

scrollReveal.js is a plugin that allows you to animate elements when scrolling a page.

Wow.js

Wow.js is another javascript plugin for controlling animation when scrolling a page.

Transit

Transit is a jQuery plugin for smoothing transitions and transformations provided in jQuery.

parallax.js

parallax.js is a plugin that reacts to the position of the smartphone in space, based on this, it controls the indentation, position and depth of layers. If the device does not have a gyroscope, then calculations are taken based on the position of the mouse cursor. In two words - advanced parallax!

Sly

Sly - JavaScript library for creating a unidirectional scroll with implemented piecewise navigation. It may seem complicated in words, I recommend just looking at an example.

Move.js

Move.js is a small JavaScript library for creating custom CSS3 animations.

slidr.js

slidr.js is an easy-to-use and lightweight JavaScript library for creating a vertical and at the same time horizontal slider.

CreateJS

CreateJS is a set of modular libraries and tools that can work together or independently to enrich content with interactivity. The functionality of these libraries will allow you to create amazing websites and applications, be sure to check out the demos.

Flippant.js

Flippant.js - JavaScript plugin for creating elements with the effect of rotation around their axis.

jmpress.js

jmpress.js is a JavaScript library with a unique idea of ​​creating a website on an endless HTML5 canvas. The idea is worthy of attention.

CSS3 libraries

Experienced developers have already taken care of creating a library with CSS3 animations for us for a long time. Now we can simply take them and apply them in our projects, and be confident in their effectiveness.

By the term “animation” we most often mean animated films - the “cartoons” we have loved since childhood. But if we look at the explanatory dictionary, we find out that translated from French it means “revival”, “animation”. And here it turns out that this meaning surprisingly accurately fits not only the film industry, but also web technologies.

Using various animation effects(transitions, movements, transformations, etc.) significantly “enliven” the website, allow you to control the user’s attention, switching it to the required element and giving certain visual cues.

Speaking about animation, one cannot fail to mention the well-known 12 principles formulated by the animators of the Disney studio, the use of which is extremely important for the reasonable and high-quality use of animation effects.

Speaking about technologies that provide using animation in web pages, there are several, but perhaps none of them is as powerful as . Just a few years ago, Flash animation technology was a formidable competitor and very popular. But now, it seems, its best years are behind it and it is gradually being replaced from the pages of sites by more powerful and flexible Java scripts. And if you decide seriously use animation on your website, then you should bet on JavaScript. And in order to make a smart choice of library, I made today’s review.

Dynamics.js

I'll probably start with Dynamics.js. This is a serious and powerful library that allows you to create physically realistic animation (such as harmonic damped oscillations of a point on the main page of a website). The library is capable of managing the properties of any DOM element. Dynamics.js is used to create menus, buttons, process indicators, markers. In this case, a wide variety of parameters are available, such as frequency, damping decrement, parameters characterizing elasticity or process duration, etc.

Cta.js

Small in volume cta.js library intended to create animation effects on the page“action-effect” type, i.e. hovering or clicking the mouse pointer over an object produces a specific effect. It is very convenient to use when developing tiled interfaces, when clicking on an element leads to its opening as a modal window, on the entire page, or as a side slide panel.

Beep.js

An interesting library that uses the WebAudio API to create a music synthesizer on a page. Can be used in developing an online music textbook or as a fun toy.

Rainyday.js

Incredibly beautiful rain effect with drops of different sizes flowing down. However, in my opinion, large drops lack realism (maybe the same physics that is present in Dynamics.js?). However, the existing API allows you to create your own objects and control their behavior, creating even more incredible effects.

Dom-Animator.js

Dom-Animator.js is a so-called “easter egg”. The effect it produces is not visible to the “naked” eye, i.e. for those who view the page in a regular browser window. But those who parse your code will see it in the console (if you still don’t understand what we’re talking about, there’s a video here that will make everything clear).

Famous

Famous - event-driven JS library for creating modern animation. It has a powerful geometric core that allows you to manipulate various 3D objects - point and volumetric - apply forces and accelerations to them, impose restrictions and control collisions.

Bounce.js

Not bad JavaScript library for creating impressive animations using CSS. Allows you to apply various types of movement, rotation, scaling and transformation to objects.

Snabbt.js

A light and fast library that, according to the developers, produces 60 fps even on mobile devices. Using transformation matrices, CSS allows you to move, rotate, scale and perform other manipulations with objects. It also allows you to apply special effects to objects that attract attention, which can be used when filling out forms.

Rekapi

Rekapi allows you to use both CSS keyframe animation(@keyframes rule) and DOM animation using JavaScript. This library allows you to create quite complex dynamic objects, such as pie and line charts, timelines and other user interface elements.

Shifty

Shifty is a library containing everything you need for a complete keyframe animation(the so-called “twinning”), and the number of objects can be simply enormous. It is a low-level library that can be used as a core for higher-level platforms or libraries. Actually, Shifty is used as the core of the aforementioned Rekapi.