Creating Web Animations with Anime.js

Creating Web Animations with Anime.js

In this article, you'll learn how to create web animations with Anime.js

There are many JavaScript animation libraries out there, but Anime.js is one of the best. It’s easy to use, has a small and simple API, and offers everything you could want from a modern animation engine. The library has a small file size and supports all modern browsers, including IE/Edge 11+.

The only thing that could stop you from using Anime.js right away is its minimal, zen-like documentation. I like the compact, structured, elegant approach it takes, but I think that a more detailed explanation would be helpful. I’ll try to fix this issue in this tutorial.

Getting Started With Anime.js

To get started, download and include the anime.js file in your HTML page:

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

Alternatively, you can use the latest version of the library hosted on a CDN:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/anime.min.js"></script> 

Now, to create an animation, we use the anime() function, which takes an object as an argument. In that object, we describe all the animation details.

let myAnimation = anime({

  /* describe the animation details */

});

There are several kinds of properties used to describe the animation. They are grouped into four distinct categories:

  • Targets – this includes a reference to the element(s) we want to animate. It could be a CSS selector (div, #square, .rectangle), DOM node or node list, or plain JavaScript object. There is also an option to use a mix of the above in an array.
  • Properties – this includes all properties and attributes that can be animated when dealing with CSS, JavaScript objects, DOM, and SVG.
  • Property Parameters – this includes property-related parameters like duration, delay, easing, etc.
  • Animation Parameters – this includes animation-related parameters like direction, loop, etc.

Let’s now see how this applies in practice. Consider the following example:

let animation = anime({
 targets: 'div',
 // Properties
 translateX: 100,
 borderRadius: 50,
 // Property Parameters
 duration: 2000,
 easing: 'linear',
 // Animation Parameters
 direction: 'alternate'
}); 

https://codepen.io/SitePoint/pen/XvEMbV

Note: I’m not going to cover the HTML and CSS sections of the code in the tutorial. These tend to be easy to grasp without additional explanation. You can find and explore the HTML and CSS in the embedded pens that follow each example.

In the above example:

  1. We select the green square (the styled div).
  2. We move it 100 pixels to the left while transforming it into a circle.
  3. We set all this to happen smoothly in two seconds (linear means that no easing will be applied to the animation).
  4. By setting the direction property to alternate, we instruct the div element to go back to its initial position and shape after animation completion. Anime.js does that by playing the animation in reverse order.

You may notice that I don’t use any units when specifying property values. That’s because if the original value has a unit, it is automatically added to the animated value. So, we can safely omit the units. But if we want to use a specific unit we must add it intentionally.

Let’s create something more meaningful.

Creating a Pendulum Animation

In this example, we will create a pendulum animation. After we “draw” a pendulum using our HTML and CSS skills, it’s time to bring it to life:

let animation = anime({
 targets: '#rod',
 rotate: [60, -60], // from 60 to -60 degrees
 duration: 3000,
 easing: 'easeInOutSine',
 direction: 'alternate',
 loop: true
});   

https://codepen.io/SitePoint/pen/bXvqVE

In this animation, we use the so-called from-to value type, which defines a range of movement for the animation. In our case, the rod of the pendulum is rotated from 60 to -60 degrees. We also use easeInOutSine easing to simulate the natural motion of pendulum which slows down at peaks and gets faster at the bottom. We use the alternate option again to move the pendulum in both directions and set the loop parameter to true to repeat the movement endlessly.

Well done. Let’s move to the next example.

Creating a Battery Charge Animation

In this example, we want to create an animated icon of a charging battery, similar to the icons on our smartphones. This is easily doable with a bit of HTML and CSS. Here is the code for the animation:

let animation = anime({
 targets: '.segment',
 width: 20,
 duration: 300,
 delay: function(el, i, l) {
   return i * 500;
 },
 endDelay: 500,
 easing: 'linear',
 loop: true
}); 

https://codepen.io/SitePoint/pen/EqEWVL

Here we have three segments (the green div elements) which expand (by increasing the width property) one after another. To achieve this effect, we need to use different delays for each one. There’s only one delay parameter we can use for an animation, so in this situation, we are going to use a function-based parameter which produces a different value for every target.

To do so, instead of a literal value, we provide a function with three arguments (target, index, and targetsLength). In our case, the function returns the index multiplied by 500 milliseconds, which causes every element to start animating half a second after the previous one.

We also use the endDelay parameter to pause for a moment before the animation starts again.

Improving the Battery Charging Animation

Now, the animation looks good, but let’s improve it a bit by adding a progress label that shows the charge percentage. Here is the code:

let progress = document.querySelector('#progress');
 
let battery = {
 progress: '0%'
}
 
let icon = anime({
 targets: '.segment',
 width: 20,
 duration: 300,
 delay: anime.stagger(500),
 endDelay: 500,
 easing: 'linear',
  loop: true
});   
 
let label = anime({
 targets: battery,
 progress: '100%',
 duration: 30000,
 easing: 'linear',
 round: 1,
  update: function() {
   progress.innerHTML = battery.progress
 },
 complete: function() {
   icon.pause();
   icon.seek(icon.duration);
 } 
}); 

https://codepen.io/SitePoint/pen/wVmJMM

This example introduces several more library features. We’ll explore them one by one.

First, we create a progress variable, which references the label in the HTML. Then we create the battery object that holds the progress property. Then, we create two animations.

The first animation is almost identical to the previous example, except for the delay parameter. Here we’ll use the Anime.js feature which allows us to animate multiple elements at once. We use the anime.stagger() function for this. In our case, anime.stagger(500) works just like the function-based parameter — it adds a 50-millisecond delay before each element animation.

In the second animation, we use the battery object as the target. Then we set the progress property to be animated to 100%. The round parameter rounds up the animated value to the given decimal. By setting it to 1, we get whole numbers.

Next, we use two of the callbacks which Anime.js offers.

To bind the progress label value from HTML with the battery progress value, we use the update() callback. We also use the complete() callback to stop the animation after the progress equals 100%, and we use the seek() method to set the animation to its completed state.

As a result, the charging animation will play until the progress becomes 100% and then it will stop and force the segments to their end animation state. The icon will appear as fully charged.

Creating More Complex Animations With Keyframes

Up until now, we’ve dealt with one-step animations that move an object from A to B. But what about moving it from A to B to C to D?

In the next example, we’ll explore how to use property keyframes to create multi-step animations. We’ll move a simple square around another one that serves as a box.

let box = document.querySelector('#box');
 
let animation = anime({
 targets: '#content',  
  translateY: [
   {value: 50, duration: 500},
   {value: 0, duration: 500, delay: 1500}, 
    {value: -53, duration: 500, delay: 500},
   {value: 0, duration: 500, delay: 2500},
   {value: 50, duration: 500, delay: 500},
   {value: 0, duration: 500, delay: 1500} 
  ],
 translateX: [
   {value: 53, duration: 500, delay: 1000},
   {value: 0, duration: 500, delay: 2500},
   {value: -53, duration: 500, delay: 500},
   {value: 0, duration: 500, delay: 2500}
  ],
 easing: 'linear',  
  begin: function() {
    box.style.borderBottom="none"; 
  },
 complete: function() {
   box.style.borderBottom="solid darkorange 3px";    
  }
});

https://codepen.io/SitePoint/pen/JgLWGa

First, we create a reference to the box element. We use it in the begin() and complete() callbacks to “open” the box at animation start and “close” it at animation end. Let’s explore how we move the other square — the content.

For each property we want to animate, we use an array of objects where each object describes a particular keyframe.

In our case, we want to move the square vertically and horizontally. So we use translateY and translateX properties and we provide a keyframes array for each of them. The trick to creating a proper movement is to compute the duration and delay parameters correctly — which can be tricky!

The frames are executed from top to bottom and start simultaneously for each property that has a specified keyframes array. Once started, how the ride will continue depends entirely on the way the duration and delay parameters are set. Good luck with the computation!

The result of our animation is that the square exits the box, makes a full orbit around it, and then goes inside again.

Creating Text Effects

We’ve seen an example of staggering above, and now we’ll explore more advanced usage. We’ll use staggering to create a cool text effect.

let animation = anime({
 targets: '.letter',
 opacity: 1,
 translateY: 50,
  rotate: {
   value: 360,
   duration: 2000,
   easing: 'easeInExpo'
 },
  scale: anime.stagger([0.7, 1], {from: 'center'}),
  delay: anime.stagger(100, {start: 1000}),
  translateX: [-10, 30]
});    

https://codepen.io/SitePoint/pen/NQYpNr

We’ve put each letter inside a span element. In the animation code, we select all letters, make them visible, and move them 50 pixels down.

Then, we rotate the letters by using a specific property parameter which defines specific parameters to a given property. This gives us more detailed control over the animation. Here, the letters will be rotated 360 degrees in two seconds applying easeInExpo easing.

In the next two properties, we use the stagger() function. We set the scale to be distributed evenly from 0.7 to 1 opacity (using the range value type), beginning from the center (using the starting position option). This makes letters smaller in the middle of the sentence and bigger at both ends.

We set the animation to wait a second before it starts (by defining a start value), and then a 100-millisecond delay is added relatively for each letter.

We intentionally add the translateX property at the end to create the desired effect, which is to rotate the letters in a spiral movement.

Creating Animations with Timelines

A timeline lets you manipulate multiple animations together. Let’s explore a simple example:

let animation = anime.timeline({
 duration: 1000,
  easing: 'easeInOutSine',
 direction: 'alternate', 
  loop: true
});          
 
animation.add({
 targets: '.one',
 translateY: -50,
 backgroundColor: 'rgb(255, 0, 0)'
}).add({
 targets: '.two',
 translateY: -50,
 backgroundColor: 'rgb(0, 255, 0)'
}).add({
 targets: '.three',
 translateY: -50,
 backgroundColor: 'rgb(0, 0, 255)'
});

https://codepen.io/SitePoint/pen/zgWZBj

In this example, we create a ball spinner.

To create a timeline, we use the anime.timeline() function. Then we define common parameters that are inherited for all added animations.

To add an animation to the timeline, we use the add() method, and then we describe the animation in the same manner we’ve already covered.

In our example, we add three animations, one for each ball. The result is that each ball rises and falls one by one.

The problem is that in this basic form, the animation seems very static. Let’s change that.

By default, each animation starts after the previous animation ends. But we can control this behavior by using time offsets. Also, if we want to make the animation more flexible and complex, we have to use animation keyframes. Let’s see how this applies in the following example:

let animation = anime.timeline({
 duration: 1000,
  easing: 'easeInOutSine',  
  loop: true
});          
 
animation.add({
 targets: '.one',
 keyframes: [
   {translateY: -50, backgroundColor: 'rgb(255, 0, 0)' },
   {translateY: 0, backgroundColor: 'rgb(128, 128, 128)'}
 ]
}).add({
 targets: '.two',
 keyframes: [
   {translateY: -50, backgroundColor: 'rgb(0, 255, 0)' },
   {translateY: 0, backgroundColor: 'rgb(128, 128, 128)'}
 ]
}, '-=900').add({
 targets: '.three',
 keyframes: [
   {translateY: -50, backgroundColor: 'rgb(0, 0, 255)' },
   {translateY: 0, backgroundColor: 'rgb(128, 128, 128)'}
 ]
}, '-=800');

https://codepen.io/SitePoint/pen/BXrWLj

Here, we remove the direction parameter, because we use keyframes to achieve the back and forth movement. We define animation keyframes by adding a keyframes parameter. As with property keyframes, each object from the array is a keyframe.

To make the balls move smoothly, we use time offsets which are specified as the second parameter to the add() function. In our case, we use values relative to the previous animation.

The result is a smooth ball spinner animation.

Conclusion

I hope that you’ve gained a much better understanding of Anime.js. To continue your learning with this foundational knowledge in hand, I recommend checking out the documentation.

Anime.js is a simple but powerful animation engine that can be used to create a broad range of animations. Let your imagination run wild.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

React vs Angular vs Vue.js by Example

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

Do we still need JavaScript frameworks?

 

 

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI