In the first tutorial of the Anime.js series, you learned about different ways of specifying the target elements that you want to animate and the kinds of CSS properties and DOM attributes that can be animated. The animations in the previous tutorial were very basic. All the target elements were just moving a certain distance or changing the border radius at a fixed speed.
Sometimes, you might need to animate the target elements in a more rhythmic manner. For example, you might have ten different elements that you want to move from left to right with a delay of 500ms between the start of the animation for each element. Similarly, you might want to increase or decrease the animation duration for each element based on its position.
In this tutorial, you will learn how to use Anime.js to properly time the animation of different elements using specific parameters. This will allow you to control the order in which an animation sequence is played for individual elements or all the elements.
These parameters allow you to control the duration, delay and easing of individual properties or a group of properties at once. The duration
and delay
parameters are specified in milliseconds. The default value for duration is 1000ms or 1s.
This means that unless specified otherwise, any animation applied to an element will be played for 1 second. The delay
parameter specifies the amount of time the animation takes to begin once you have already triggered it. The default value for delay is 0. This means that the animations will begin as soon as they are triggered.
You can use the easing
parameter to control the rate at which an animation is played for the duration it is active. Some animations start out slow, pick up pace in the middle, and then slow down again at the end. Others start at a good pace and then slow down for the rest of the time.
However, in all the cases, the animation always completes within the time specified using the duration
parameter. Anime.js provides a lot of easing functions that you can apply to your elements directly by only using their names. For some easing functions, you can also set a value for the elasticity
parameter to control how much an element's value bounces back and forth like a spring.
You will learn more about different easing functions in the final tutorial of the series. The following code snippet shows how to apply all these parameters to different animations.
var slowAnimation = anime({ targets: '.square', translateY: 250, borderRadius: 50, duration: 4000 }); var delayAnimation = anime({ targets: '.square', translateY: 250, borderRadius: 50, delay: 800 }); var cubicAnimation = anime({ targets: '.square', translateY: 250, borderRadius: 50, duration: 1200, easing: 'easeInOutCubic' });
As you can see, these parameters can be used independently of other parameters or in combination with them. The cubicAnimation
has both the duration
and easing
parameter applied to it. If the duration had not been specified, the animation would have run for 1 second. Now, it will run for 1,200 milliseconds or 1.2 seconds.
One major limitation of property parameters in the above example was that all the animations of the target element will have the same duration
, delay
and easing
values.
This may or may not be the desired behavior. For example, instead of translating and changing the border radius of the target element at the same time, you might want to first translate the target element and then animate its border radius. Anime.js allows you to specify different values for the duration
, delay
, easing
and elasticity
parameters for individual properties. The following code and demo should make it clearer.
var indiParam = anime({ targets: '.square', translateY: { value: 250 }, rotate: { value: '2.125turn' }, backgroundColor: { value: 'rgb(255,0,0)', duration: 400, delay: 1500, easing: 'linear' }, duration: 1500 });
In the above code, all the properties that we want to animate have different values. The background color animation has a duration of 400ms, while the rotation and translation animations use the global duration value of 1500ms.
The background color animation also has a delay so any change in the color only starts after 1500ms have passed. The rotate
and translateY
properties use the default value for the delay
and easing
parameters because we have neither provided a local nor a global value for them.
Property-based parameters are helpful when you want to change the order and duration for animating individual properties. However, the same duration
and delay
will still be applied for individual properties on all the target elements. Function-based parameters allow you to separately specify the duration
, delay
, elasticity
and easing
for different target elements in a compact manner.
In this case, you set the values of different parameters using functions instead of numbers. These functions accept three parameters: target
, index
, and targetCount
. The target
parameter stores the reference to the current target element. The index
parameter stores the index or position of the current target element. The targetCount
parameter stores the total number of target elements.
The target
parameter is useful when the animation values need to be set based on some attributes of the target element. For example, you can store the delay
, duration
or easing
values for a target element in data attributes and then access them later.
Similarly, you could access the background color of a target element and then manipulate it to set a final unique color value for individual elements. In this way, you could animate all the elements to have a background color that is 20% darker than their current color.
The index
parameter gives you the position of the current target in our list of target elements. You can use it to gradually change the value for parameters like duration
and delay
for different elements.
This is generally useful when you want to set the values in ascending order. You can also subtract the index
from the targetCount
to set the values in descending order. The following code snippet uses both these parameters to specify the values in ascending and descending order.
var delaySequence = anime({ targets: '.square', translateY: 250, delay: function(target, index) { return index * 200; } }); var delaySequenceR = anime({ targets: '.square', translateY: 250, delay: function(target, index, targetCount) { return (targetCount - index) * 200; } });
The following code sets a different easing
value for each target element using the index
parameter.
var easeInValues = ['easeInQuad', 'easeInCubic', 'easeInQuart', 'easeInQuint', 'easeInSine', 'easeInExpo', 'easeInCirc', 'easeInBack', 'easeInElastic']; var easeInSequence = anime({ targets: '.square', translateY: 250, duration: 2000, easing: function(target, index) { return easeInValues[index]; }, autoplay: false });
This last set of parameters allows you to specify the number of times an animation should be played and the direction in which it should be played. You can specify the number of times an animation should be played using the loop
parameter. There is also an autoplay
parameter which can be set to true
or false
. Its default value is true
, but you can stop the animations from starting by themselves by setting it to false
.
The direction
parameter controls the direction in which the animation is played. It can have three values: normal
, reverse
, and alternate
. The default value is normal
, which keeps the animation playing normally from the start values to the finish values. Once the target elements reach the finishing value, if the loop
value is greater than 1, the target elements jump back abruptly to the start values and then begin the animation again.
When the direction
is set to reverse
and the loop
value is greater than 1, the animation gets reversed. In other words, the target elements start the animation from their final state and go backwards to reach the initial state. Once they are in the initial state, the elements jump back to the final state and then again start the reverse animation. The alternate
direction value changes the animation direction after every loop.
var normalLoop = anime({ targets: '.square', translateY: 250, delay: function(target, index) { return index * 200; }, loop: 4, easing: 'easeInSine', autoplay: false });
In the following demo, I have set the number of loops to four so that you can easily notice the difference in animation of the elements in different modes.
In this tutorial, you learned about different kinds of parameters that can be used to control the animation of target elements in Anime.js. The property parameters are used to control the animation of individual properties.
You can use them to control the sequence in which the animation is played for individual elements. The function parameters allow you to control the timing and rate of animation for individual elements with respect to the whole group. The animation parameters allow you to control how the animation itself is played for different elements.
If you have any questions related to this tutorial, please let me know in the comments.
14 Best PHP Event Calendar and Booking Scripts
/20 Best WordPress Calendar Plugins and Widgets
/Create a Blog for Each Category or Department in Your WooCommerce Store
/Best Affiliate WooCommerce Plugins Compared
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/20 WordPress Video Plugins and Players to Add Engagement
1 /Short Course: Better Angular App Architecture With Modules
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/15 Best PHP Event Calendar and Booking Scripts
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /Creating Pretty Popup Messages Using SweetAlert2
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Introduction to API Calls With React and Axios
/A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How Laravel Broadcasting Works
/Getting Started With Redux: Why Redux?
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
/12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/Introduction to the CSS Grid Layout With Examples
1 /8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/Eloquent Mutators and Accessors in Laravel
1 /A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Understanding Recursion With JavaScript
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Creating Your First Angular App: Basics
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/How to Auto Update WordPress Salts
/How to Download Files in Python
/10 Best WordPress Star Rating Plugins
/10 Best HTML5 Sliders for Images and Text
/Creating a Task Manager App Using Ionic: Part 2
/Introduction to Forms in Angular 4: Reactive Forms
/Deferring Tasks in Laravel Using Queues
/Introduction to Forms in Angular 4: Template-Driven Forms
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/Understanding ExpressJS Routing
/Inheritance and Extending Objects With JavaScript
/Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
/Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
/Performant Animations Using KUTE.js: Part 1, Getting Started
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/Build Web Applications Using Node.js
/New Course on WordPress Conditional Tags
/Stateful vs. Stateless Functional Components in React
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/API Authentication With Node.js
/Command Line Basics and Useful Tricks With the Terminal
/Learn Computer Science With JavaScript: Part 3, Loops
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Learn Computer Science With JavaScript: Part 1, The Basics
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/How to Create a Real-Time Feed Using Phoenix and React
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/JavaScript-Based Animations Using Anime.js, Part 2: Parameters
JavaScript-Based Animations Using Anime.js, Part 1: Targets and Properties
/20 Popular WordPress User Interface Elements
/Angular vs. React: 7 Key Features Compared
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
/Getting Started With Matter.js: The Body Module
/Getting Started With Matter.js: The Engine and World Modules
/Getting Started With Matter.js: Introduction
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
Using Celery With Django for Background Task Processing
/Dynamic Page Templates in WordPress, Part 3
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
/The 5 Best IDEs for WordPress Development (And Why)
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/Building Your Startup: Approaching Major Feature Enhancements
/Extending HTML by Creating Custom Tags
/How to Define State With Angular UI-Router
/Dynamic Page Templates in WordPress, Part 2
/Dynamic Page Templates in WordPress, Part 1
1 /Building Your Startup: Securing an API
/How to Draw Bar Charts Using JavaScript and HTML5 Canvas
/What Is WP-CLI? A Beginner’s Guide
/How to Zip and Unzip Files in CodeIgniter
/Programming With Yii2: Building Community With Voting, Comments, and Sharing
/How to Work With Session Data in CodeIgniter
/How to Use the jQuery Function to Select Elements
/How to Create Animations in AngularJS With ngAnimate
/AngularJS Form Validation With ngMessages
/15 Best PHP Calendar, Booking & Events Scripts
/Building Your Startup: Using Routes for Schedule With Me
/A Quick Guide to Dependency Management With Bower
/Using the Twitter API to Tweet Repetitive Content
/Getting Started With Chart.js: Scales
/New Short Course: React State Management With MobX
/Building Your Startup: Leveraging Bootstrap, Ajax, and jQuery
/How to Create a Laravel Helper
/Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts
/Getting Started With Chart.js: Radar and Polar Area Charts
/How to Set Up a Project in Angular 2
/Getting Started With Chart.js: Line and Bar Charts
/How to Handle Errors & Exceptions in the Yii Framework
/Getting Started With Chart.js: Introduction
3 /Building Your Startup With PHP: Bootstrap Your Home Page
/How to Build a User Tour With Shepherd in JavaScript
/Building With the Twitter API: Analyzing Your Followers
/How to Use the WordPress REST API’s Index Route
/Programming With Yii2: Building a RESTful API
/New Course: How to Use the Google Maps API
/Uploading With Rails and Carrierwave
/How to Use OmniAuth-Twitter in a Rails Application
/Uploading Files With Rails and Dragonfly
/Making a Sliding Side Navigation Menu for Responsive Designs
/Building With the Twitter API: Creating Friends to Follow
/Building Your Startup: Running Multiple Domains
/Using the Requests Module in Python
5 /Acuity Scheduling Developer Platform: OAuth, Webhooks, and Reporting
/Decoding the Proxy Class in OpenCart
/Acuity Scheduling: Embedding and Developer Integration
1 /Custom Controllers in OpenCart 2
/Building Your Startup: Error Logging
/Acuity Scheduling’s Developer-Friendly Scheduling Service
/New Short Course: Essential Gulp Tasks
/Erlang and Elixir, Part 5: Phoenix Framework
/Add a Website Calendar Using Jalendar 2
/Getting Started With Cassandra: Using CQL API and CQLSH
/Using the New York Times API to Scrape Metadata
1 /New Coffee Break Course: How to Animate Your Angular 2 App
/Make Creating Websites Fun Again With Hugo
/Get a Fake REST API Up and Running Using json-server
/Understanding Nested Routing in React
/Authentication in Rails Using Clearance
/Using Illuminate Database With Eloquent in Your PHP App Without Laravel
/New Coffee Break Course: How to Use the Angular 2 HTTP Service
/Get Started Building Your Blog With Parse.js: Migration to Your Own Parse Server
/Building Your Startup: Automatic Time-Zone Detection
/Adding Custom Fields to Simple Products With WooCommerce
/New Coffee Break Course: Reactive Programming With RxJS
/Using Namespaces and Autoloading in WordPress Plugins, Part 4
/New Code eBooks Available for Subscribers
/
harriett What's up, after reading this awesome…