After completing the first three tutorials of the series, you should now be very comfortable with a lot of Anime.js features. The first tutorial showed you how to select target elements. In the second tutorial, you learned about different types of parameters that can be used to have fine control over the delay and duration of animations of different elements. The third tutorial focused on learning how to have greater control over the values of a single property during the course of the animation.
In this tutorial, you will learn about different callbacks that can be used to execute a function based on the progress of the animation. Almost every example in the previous tutorials used CSS properties to demonstrate how different methods and parameters work. This might have given you the idea that the library is more suited for animating CSS properties. This time, we will have a section dedicated to the creation of interesting SVG-related animations in Anime.js.
As I mentioned in the introduction, you can use callbacks to execute functions based on the progress of the animation. There are four different callbacks: begin
, run
, update
, and complete
. Each callback function is fired at a specific time, and each one accepts an animation object as its argument.
The begin()
function is called when the animation actually begins. This means that if an animation has a delay of 800ms, begin()
will be called only after that delay is over. You can check if an animation has begun playing or not using animationName.begin
, which will return true
or false
respectively.
The run
callback can be used to execute a function in every frame after an animation actually starts playing. If you want to execute a function in every frame from the very beginning of the animation irrespective of its delay
, you should use the update
callback instead.
The complete
callback is similar to begin
except for the fact that it is called once the animation has finished playing. Just like begin
, you can use animationName.complete
to check if an animation has finished playing or not.
You have already seen in the first tutorial how to use the update
callback while animating numerical values of a JavaScript object. In this tutorial, we will modify that example and see how to use all these callbacks together to provide more information to the user.
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..."; } });
I have intentionally added some delay in this animation so that we can notice the difference in the timing of the execution of different callbacks. The update
callback starts executing its function as soon as the animation instance begins.
The actual animation starts playing after 1000ms, and that's when the begin
function shows its "Starting the Scan..." message to the user. The run
function also starts executing at the same time and updates the numerical values of the object after every frame. Once the animation has finished, the complete
callback shows a "Scan Complete..." message to the user.
Easing functions can be used to control how the value of a property transitions from its initial value to its final value. These easing functions can be specified using the easing parameter, which can accept strings as well as custom Bézier curve coordinates (in the form of an array).
There are 31 different built-in easing functions. One of them is linear
, and the other 30 consist of ten different variations of easeIn
, easeOut
, and easeInOut
. There are three elastic easing equations called easeInElastic
, easeOutElastic
, and easeInOutElastic
. You can control their elasticity using the elasticity
parameter. The value of elasticity
can be anywhere between 0 and 1000.
EaseIn
equations accelerate the value change of the property starting from zero. This means that the change in value would be slow in the beginning and very quick at the end. The rate of change is zero in the beginning and maximum at the end. EaseOut
equations decelerate the value change of the property starting from the maximum rate change.
This means that the change in value would be very quick in the beginning and very slow at the end. EaseInOut
equations accelerate the rate change in the beginning and decelerate it at the end. This means that the rate of change will be slow in the beginning as well as the end, and it will be fastest in the middle of the animation. The following demo shows the difference in the rate of change for each of these easing functions.
You can also add your own custom easing functions to the built-in list with the help of anime.easings
. Here is an example of creating custom easing functions.
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 });
All the motion-related animations that we have created until now moved the target elements in straight lines. It is also possible in Anime.js to move an element along a complex SVG path with lots of curves. You can control both the position and the angle of the animating elements on the path. To move an element to the x coordinate of the path, you can use path(x)
. Similarly, an element can be moved according to the y coordinate of the path using path(y)
.
Unless the path is a straight line, it will almost always form an angle with respect to the horizontal base line. If you are rotating any non-circular element, it will feel more natural if the element follows the angle of the path. You can do so by setting the rotate
property to be equal to path('angle')
. Here is the code that animates four elements with different easing values along an SVG path.
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; }, duration: 10000, loop: true });
You can see in the following demo that the red square with easeInCubic
easing is slowest in the beginning and the fastest at the end. Similarly, the orange square with easeOutCubic
is the fastest in the beginning and the slowest at the end.
You can also animate the morphing of different SVG shapes into one another using Anime.js. The only condition is that both the shapes should have the same number of points. This means that you can only morph triangles into other triangles and quadrilaterals into other quadrilaterals. Trying to morph between an unequal number of polygon points will result in an abrupt shape change. Here is an example of morphing a triangular shape.
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 more interesting effect that you can create with SVG is line drawing. All you have to do is give Anime.js the path that you want to use for line drawing and other parameters that control its duration, delay, or easing. In the following demo, I have used the complete
callback to fill the line drawing of the Font Awesome anchor icon with a yellow color.
var lineDrawing = anime({ targets: 'path', strokeDashoffset: [anime.setDashoffset, 0], easing: 'easeInOutCubic', duration: 4000, complete: function(anim) { document.querySelector('path').setAttribute("fill", "yellow"); } });
Combining the knowledge of all the concepts that you have learned so far, you can create more complex line drawings with much better control over the way they are drawn. Here is an example in which I have written my own name using SVG.
var letterTime = 2000; var lineDrawing = anime({ targets: "path", strokeDashoffset: [anime.setDashoffset, 0], 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.setAttribute("stroke", "black"); letters.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 });
I begin by assigning the value 2000 to the variable letterTime
. This is the time that I want Anime.js to take while it draws each letter of my name. The delay
property uses the function-based index parameter to set an appropriate delay
value with the help of the letterTime
variable.
The index of the first letter "M" is zero, so Anime.js starts drawing it immediately. The letter "O" has a delay of 2000ms because that's the amount of time it takes to completely draw the letter "M".
Inside the begin
callback, I have set the stroke
value of all the letters to black
and their fill
values to none
. This way we can clear all the color values applied inside the update
callback so that the letters can return to their initial state when run in multiple loops. Try clicking the Write the Name button in the following demo to see the code in action.
In this tutorial, you learned about different callback functions that can be used to perform tasks like updating the DOM or changing the value of an attribute based on the animation progress. You also learned about different easing functions and how to create one of your own. The final section of the tutorial focused on creating SVG-based animations.
After completing all four tutorials of the series, you should now have enough knowledge of Anime.js to create some interesting effects for your next project. If you have any questions related to this tutorial, please let me know in the comments.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/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
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/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
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /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 to Create a Custom Settings Panel in WooCommerce
/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
/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
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/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
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/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
/Introduction to API Calls With React and Axios
/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
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/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
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant 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
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/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
/New Course on WordPress Conditional Tags
/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 RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/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
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/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 2
/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
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/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 9 API
/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
/Learn to Code With JavaScript: Part 1, The Basics
/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 Engine and World Modules
/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
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…