Animation with a car in javascript. Promising JavaScript libraries and plugins for animation

By the term “animation” we most often mean animated films - the “cartoons” we have loved since childhood. But if you look into Dictionary, then we learn 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 quality use animation effects.

Speaking about technologies that provide using animation in web pages, several can be distinguished, 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 that she best years behind and it is gradually being replaced from website pages 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 accurate animations (such as harmonic damped oscillations points on home page site). 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. Very convenient to use during development tiled interfaces, when clicking on an element causes it to expand as modal window, full page, or as a sidebar slide.

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 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 the so-called " Easter Egg"(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 With using CSS. Allows you to apply to objects different kinds movement, rotation, scaling and transformation.

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 when JavaScript help. 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 huge. 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.

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 SVG animations-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, an animation delay was intentionally added so that you could notice the difference in execution time different functions callback. 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 the transition from the initial value of a property to the final value. 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:

With anime.easings you can create native functions smoothness. 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 of 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 function to fill the anchor drawing from Font Awesome yellow color.

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 ));

There is a misconception among web developers that CSS animation is the only productive way to animate on the web. This myth has led many developers to abandon JavaScript-based animation altogether. Thus:

  1. Forced yourself to manage complex interaction UI in style sheets
  2. Blocked yourself in Internet support Explorer 8 and 9
  3. Forgoes the ability to build motion physics, which is only possible in JavaScript

Real-life testing: based on JavaScript animation as fast as CSS-based animations - sometimes even faster. CSS animation generally only has an advantage over jQuery's $.animate(), which is inherently very slow. However, JavaScript animation libraries that bypass jQuery show incredible performance while avoiding DOM manipulation as much as possible. These libraries can be up to 20 times faster than jQuery.

So, let's dispel some myths, dive into some real examples animations and improve our programming skills in the process. If you love developing practical UI animations for your projects, then this article is for you.

Why JavaScript?

CSS Animations are useful when you need to make property transitions in your stylesheets. Plus, they deliver fantastic performance out of the box - without adding a library to the page. However, when you use CSS transitions to drive a rich motion design (like you'll see in latest versions iOS and Android), they become too difficult to manage, or their functions are simply riddled with errors.

Ultimately, CSS animations limit you to a specific specification. In JavaScript, by the very nature of any programming language, you have an infinite amount of logical control. JavaScript animation engines leverage this fact to provide new features that allow you to do some very useful things:

Note: If you are interested in the topic of performance, you can read Julian Shapiro's “CSS vs. S Animation: which is faster?” and Jack Doyle: “Busting the Myth: CSS Animations vs. JavaScript" . For performance demos, refer to the performance panel in the Velocity documentation and the GSAP "Speed ​​Comparison Library" demo.

Velocity and GSAP

The two most popular JavaScript animation libraries are Velocity.js and GSAP. Both work with and without jQuery. There is no performance penalty when using these libraries with jQuery because they completely bypass the jQuery animation stack.

If jQuery is present on your page, you can use Velocity and GSAP just like jQuery's $.animate(). For example, $element.animate(( opacity: 0.5 )); it just becomes $element.velocity(( opacity: 0.5 )).

These two libraries also work when jQuery is not present on the page. This means that instead of chaining the animation call into a jQuery object element - as simply shown - you would pass the target element(s) to the animation call:

1
2
3
4
5

/* Working without jQuery */

Velocity(element, ( opacity: 0.5 ) , 1000 ) ;

//Velocity

TweenMax.to(element, 1, (opacity: 0.5));

// GSAP As you can see, Velocity retains the same syntax as jQuery's $.animate(), even when used without jQuery; simply shift all parameters to the right one position to create space for passing in the intended elements in the first position. GSAP, on the other hand, uses an object-oriented API design, as well as user-friendly

static methods . This way, you can have full control over the animations. In both cases you are no longer animating the object jQuery element, but rather a raw DOM node. As a reminder, you access raw DOM nodes using document.getElementByID , document.getElementsByTagName ,

document.getElementsByClassName

or document.querySelectorAll (which works the same for jQuery's selector mechanism). We will work with these functions in the next section.

Working without jQuery

(Note: If you need a basic primer on jQuery's $.animate(), check out the first few sections in the Velocity documentation.) Let's explore querySelectorAll because this is probably the weapon you'll be using when selecting elements without jQuery: As shown you simply pass querySelectorAll

1
2
3
4
5

CSS selector
(the same selectors you would use in your style sheets) and it will return all matching elements in an array. Hence you can do this:
/* Get all div elements. */
var divs = document.querySelectorAll("div");
/* Animate all divs at once. */

Velocity(divs, ( opacity: 0.5 ) , 1000 ) ;

//Velocity

TweenMax.to(divs, 1, (opacity: 0.5));
// GSAP
Since we no longer attach animations to jQuery element objects, you may be wondering how we can chain animations together:

There is no performance disadvantage to animating this path (you cache the element being animated to a variable, rather than having to repeatedly make querySelectorAll selections on the same element).

(Hint: With the Velocity UI Pack, you can create your own multicall animations and give them custom names that you can later use as the first Velocity parameter. See the Velocity UI Pack documentation for more information.)

Velocity's call-to-process-at-a-time has a huge advantage: if you use promises with your Velocity animations, then each Velocity call will return an effective promise object. You can learn more about working with promises in Jake Archibald's article. They are incredibly strong.

In the case of GSAP, its expressive object-oriented API allows you to place your animations on a timeline, giving you control over scheduling and timing. you are not limited to chain animations; you can nest timelines, make animations overlap, etc:

The awesomeness of JavaScript: Workflow

Animation is essentially an experimental process that requires playing with timing and easing to get the right feel the application needs. Of course, even if you think the design is great, the client will often request non-trivial changes. In these situations, managed workflow becomes important.

While CSS transitions While quite simple to insert into a project for effects like hovering, they become unmanageable when you try to sequence even moderately complex animations. This is why CSS provides keyframe animation, which allows you to group animation logic into sections.

However, the basic drawback of the Keyframe API is that you have to define sections in percentage terms, which is not intuitive. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

@keyframes myAnimation (
0 % {
opacity: 0 ;
transform: scale(0 , 0 ) ;
}
25 % {
opacity: 1 ;
transform: scale(1 , 1 ) ;
}
50 % {
transform: translate(100px, 0 ) ;
}
100 % {
transform: translate(100px, 100px) ;
}
}

#box (
animation: myAnimation 2.75s;
}

What happens if the client asks you to make the translateX animation a second longer? This requires rebuilding the math and changing all (or most) of the percentages.

In this article, we would like to introduce you to some of the most useful JavaScript libraries that can be used to animate the content of web applications. These libraries are designed to create animations for drop-down menus, sliding elements, parallax animations, and even fonts.

And the main thing is that everything is 100% free resources with open source code, so you can use them in any of your projects.

1.Dyanamic.js

Just enable dynamics.js on the page and then you can animate CSS properties on any DOM element. You will also be able to animate SVG properties.

Dynamics.js contains its own setTimeout property. The reason is that requestAnimationFrame and setTimeout have different behavior. Property supported by everyone JavaScript objects. The library has been tested for compatibility with Safari 7+, Firefox, Chrome 35+ 34+, IE10+.

2. Animate Plus


Productive JavaScript library, which helps you animate CSS properties and SVG attributes.

Animate Plus is great for organizing quick interaction of all interface controls, as well as long sequences animations for desktop and mobile devices.

3. Cta.js


Compact, productive JavaScript library to animate any element (“action”) inside any other element (“effect”) on the page.

4. Beep.js


Beep.js is a set of tools for creating browser-based JavaScript synthesizers using the WebAudio API.

5. Iconate.js


Productive JavaScript library animation and transformation of cross-browser icons. iconate.js also supports AMD and CommonJS modular templates.

6.Dom Animator



JavaScript library to display small ASCII animation elements in DOM comments. This is a standalone library that uses only JavaScript ( animation is done in comment nodes, in DOM only).

7.Rainyday


Rainyday.js allows you to create realistic-looking raindrop effects on glass using HTML5 canvases and JavaScript. The library includes an extensible API and built-in error detection.

Rainyday.js uses the power of HTML5, so it is supported by most modern browsers.

8. Anima.js


Anima.js allows you to use delays and durations, even for CSS animations. The library is used to create animation CSS Transformations and 3D transformation with Javascript enabled. You can start, stop, cancel animations, and even create event-driven effects.

9. blinkTitle.js


blinkTitle.js can create a blinking HTML title, alert or notification in the title.

10. Snabbt.js


Javascript library designed to move elements, offset, rotate, scale, tilt, and resize. Thanks to matrix multiplication operations, transformations can be combined in any combination you want. The final result is then specified using CSS3 transformation matrices.

11. Vivus


Vivus is a compact JavaScript class ( no dependencies) to animate SVGs by drawing. Vivus contains many various effects animation, the ability to create a custom script has been implemented.

12. Impulse


JavaScript library to build dynamic interactions based on real physics, with an emphasis on mobile devices. Instead of animation properties that specify a period of time, Impulse changes position and speed. It does not contain large quantity dependencies. Doesn't require jQuery, but can interact nicely with it.

13. Ani.js


AniJS is declarative JavaScript library for processing CSS animations. It is fully documented and easy to use.

14. Bounce.js


A tool for creating beautiful keyframe animations based on CSS3. Add a component, select an option and get a short URL or export the code to CSS.

15. Sticker.js


Sticker.js is JavaScript library, which allows you to create peel-off sticker effects. The library works most of the time popular browsers, which support CSS3 ( including IE10+). Distributed under MIT license License.

16. Wow.js


WOW.js displays CSS animation as you scroll down the page. By default, you should use this action to run animate.css, but you can easily change these settings.

17. Parallax.js


Parallax.js is a compact solution for creating parallax effects. The library also works on smartphones and tablets ( with gyroscope or hardware motion detector). Parallax.js has several options to customize the effect using " data attributes"or via JavaScript. The library can work standalone or as JQuery plugin and Zepto ( there are two versions).