What do you want to learn?
Leverged
jhuang@tampa.cgsinc.com
Skip to main content
Pluralsight uses cookies.Learn more about your privacy
SVG Animation with JavaScript
by Eva Ferreira
You feel comfortable with SVG and CSS animations, but there’s something missing, isn't there? Because CSS animations can take us only so far. If you wish to take your animation skills to another level, SVG Animation with JavaScript is the course...
Resume CourseBookmarkAdd to Channel
Table of contents
Description
Transcript
Exercise files
Discussion
Recommended
Course Overview
Course Overview
(music) Hi everyone. My name is Eva Ferreira and welcome to my SVG Animation with JavaScript course. I am a front-end developer and goal developer expert who loves animation. In this course we are going to learn how to animate illustrations using JavaScript. Some of the major topics that we will cover include how to prototype animations from the original idea to getting the right assets, how to correctly export and optimize your SVGs using Adobe Illustrator, how to choose the correct library for your project from native libraries to external resources, how to animate using the GreenSock animation platform and how to export animations from After Effects into fully functional code with just a few clicks. By the end of this course you will know how to build animations from the ground up using not only JavaScript, but also your creativity in the full process. Before beginning the course you should be familiar with basic JavaScript and SVG. I hope you will join me in this journey to learn animation with the SVG with JavaScript Animation course at Pluralsight.
Getting Started
Animation Techniques
Hello and welcome to the SVG Animation with JavaScript course. In this course we'll learn how to animate pictographics using JS and more specifically how to animate them using GreenSock. But first of all let's talk about the different animation techniques that are available so we can pick the right tool for every animation project. There are two types of animation techniques. The native and the external. The native options are a way of animating without any additional scripts using everything the browser has to offer, and external are different libraries, mostly JavaScript, that we can use to animate faster and with better browser support. If we look into the native category we can find CSS, which is an amazing way of animating without too much trouble and with great performance. We should also mention SMIL which has been around for a while, but is currently being deprecated in some browsers. There is also the Web Animations API. This is a way to animate HTML and SVG by using JavaScript. It doesn't have a great browser support yet, but you can use a polyfill and when it comes to external libraries we can find hundreds of different options. The most common ones are Velocity.js, GreenSock, and BodyMovin.
Native Animations
Let's take a closer look at the native animation techniques available. The most common way to animate SVG is using CSS. There are good parts and bad parts. The good part about these kind of animations is the low learning curve. If you have been around in the web development world for a while you have probably used CSS more than once. CSS animations are really easy to apply and configure. You first create the keyframes and then you apply the animation to an element. For example, let's change the opacity of this rectangle from 0 to 1. First, we will name this animation and then we will apply it using the animation properties, name and duration. The most useful part of CSS animations is that they can be reused multiple times. You can use the same animation over and over again. You can call it by its name and apply different durations or directions. You also have very good browser support. They work almost everywhere. And performance is great for the very reason that they are native to the browser. If you wish to be sure that the performance is always the best, animate the opacity or transform properties. Neither of these causes any layout operations and therefore perform much better than using position relative and top-left properties or width or height values. Check out csstriggers.com to see a full list of CSS properties and their impact in the browser. It is also worth mentioning that motion along a path is on its way to browser support. You can use it today in Chrome browser. All you need is an SVG path and a keyframe animation. Check out some examples and information on csstricks.com. The bad parts are that this technique of animation has a few limits. For example, the easings available in CSS are quite limited. To compare these easings I recommend you the cubic-bezier.com website by Lea Verou. In here we can try the five pre-defined easings. Ease, which is the default; linear, that means no acceleration; ease-in, ease-out, and ease-in-out. And also we can create a new one using these controllers. Even though we can create interesting bouncing effects using the cubic-bezier function, we are not even close to the unlimited quantity of easings that we are able to create through JavaScript. If you go to the GreenSock website there is an ease visualizer which you can use to find the easings available. Another worth mentioning is staggering, but in one animation after the other. This is 100% doable in CSS. You can create multiple animations and link them using delays equivalent to the duration of the previous animations. Even though this works, it isn't very dry. If we wish to change the relation of the first animation we need to rewrite the delays. Doing this once or twice is not very hard, but in large-scale projects this can turn into a problem. The last item to mention is the behavior can differ from one browser to the other. For example, when we use SVG and we apply transformations to these values we can find that the transform origin sometimes behaves differently in Chrome or in Firefox browsers. If we use relative positioning such as center or 50% it will want to fix this and we need to write absolute positionings, like for example 340px and 12px. JavaScript frameworks take care of all these and fix these by default. SMIL know as Synchronized Multimedia Integration Language can be another approach to animate SVG. There are again good parts and bad parts. The first good is that it has a low learning curve. It does have good performance, but in this case the bad parts overcome the good because SMIL is losing browser support. Not only is it being deprecated in Chrome, but also Microsoft Edge has no plans to implement it. Finally, let's take a look at the Web Animations API. This is a new JavaScript API for driving animate content on the web. It uses JavaScript to show in the animation features of SVG and CSS. The current browser support might not be the best, but the future is looking bright as more browsers are moving toward implementation. It affords good performance and a lot of documentations are available. If you are getting started, you should definitely go watch Alice in Web Animations API Land, a talk by Rachel Nabors. The bad parts are basically the high learning curve because it requires JavaScript and let us not forget that that means that we need to have programming skills and the little support it has today. But I believe it has a great future so let's take a look. To animate an element with the Web Animations API, you need to use the animate method. It takes the keyframes and the duration as parameters, but you can also add direction or iteration options among others. (Typing)
External Libraries
Let's take a look at some of the external libraries available. First of all, we have Velocity JS. Velocity JS syntax looks a lot like jQuery so if you are used to using this technology it won't be very hard for you to add that to this animation framework. It has a great documentation in the official website and it animates separated transform properties, a very useful feature currently not available in CSS. The performance is not the best, especially if we compare it to GreenSock. GreenSock is the main library we will be using in this course. It also works with separated transform properties. It has a great documentation and a big community that can help you in anything you need. The performance is great and it automatically fixes the different cross-browser on SVG transformations. The bad part of GreenSock is that some features are not free. Then there's BodyMovin. BodyMovin is an After Effects extension that exports your animations in web format. It has a low learning curve even though we must consider that you should know how to use After Effects. It is performant and the bad parts are that you need an After Effects license and you don't always have full control of the result. In the next part of the course we will work on how to plan animations, how to export the illustrations, and how to animate them using GreenSock and BodyMovin.
Prototyping and Setup
Prototyping and Set Up
In this part of the course we will be talking about the process before an animation gets into the browser. We will learn how to prototype an idea using tools such as storyboards and scripts and how to identify the assets we will be needing. Later on we will find those assets and learn how to export them using Adobe Illustrator. First of all, let's talk about the different animation types available. Defining the type of the animation we want to create will help us achieve a better result. Every animation and transition should have a purpose. Our first type of animation is the user interface animation. This is the most significant animation you can add to your website. UI animations provide meaningful information to users. These include loaders, spinners, hints on correct and incorrect inputs and many, many more. I highly recommend you to get information from CodePen Patterns where you will find amazing examples of UI animations. Our second type of animation is the storytelling animation. These are ideal to instruct the user on how to use a new app, a new feature, or simply escort them through a process. One wonderful example of this type of animation can be seen on MailChimp every time you send an email. If you are not familiar with it, I recommend you watch this talk by Eric Muntz at ColdFront 2017 where he shows the way MailChimp does the storytelling animations or read about another one the historical animations in this blog post. These animations can be harder to implement, but they are extremely useful for the user. This might seem silly or useless, but there's nothing wrong with animating a flying unicorn from time to time. What's commonly known as useless animation is actually a great way to practice new techniques and build a portfolio. You don't really need any skills to animate. We will be working with this kind of animation today.
Storyboards and Scripts
Now that we have decided which kind of animation we will be doing, it's time to prepare our story. Even if this feels a little farfetched, if we are working on a UI animation it's very important not to miss this step since it will prepare us for coding time. There are two main types of preparation we can do, scripts and storyboards. It is ideal to do both, but as long as we prepare one we will be ready to animate. Let's take a look at the difference. The script is written text. It is commonly used in movies or short films to describe what is going to happen each second of the animation. In this paper we should tell the story of our animation from the beginning to the end. We should also focus on how our camera or screen is going to show each part of our characters. On the other side we have a storyboard. This is a set of sketches that will describe this story in a more graphical way than the script. You don't need to be an expert illustrator to do this. Some fast sketches will be enough to cover the story and have a great insight on how each frame will look. Okay, you might be wondering at this point why would we bother with these things? We're not making a movie, I know, but the truth is that there are a few reasons why making a storyboard or a script will actually help you when animating for the browser. First of all, it will let us focus on the story instead of the technology. Animations need to add value to the user and that value is inside the story. Once we focus on the story we will be able to create an interesting story line that goes with it and we will define the frames and field sizes that we will be coding later on. We use different field or shot sizes to show the user exactly what they should be focusing on. You can learn about the most common ones on learnaboutfilm.com. You can have an example of how shot sizes work on the web inside the involving process of tumble.com. See how they use different techniques to make the user focus on the most important content. And storyboards and scripts are not only good for the story itself, they also have a very important role in the planning of the whole animation process. It will let us know the difficulty level of the project and estimate how long it will take. And last but not least, thanks to the storyboard we will be able to see very quickly which assets we will need. So let's move on to the next video where we will learn how to find those assets and export them in Adobe Illustrator.
Preparing Assets
Now we are ready to go find our assets and prepare them for export. During this part of the course we will be using Adobe Illustrator. You can find it on adobe.com. If you prefer to use an open source alternative I'd recommend Inkscape, which will work just the same for this project. For this occasion we will be using this cute cats illustration from freepik.com and more specifically this cat. You can find the file in the course assets, but if you get into the website you can find a lot of different illustrations that are ideal for animation. Just look for animation or well, why not, kittens. Open the file on Adobe Illustrator and let's get to work. We want to achieve a cleaner code and to do this we need to follow a few instructions. First of all, we need to reorder the illustration to our needs and delete everything unnecessary. So once we open our file in Illustrator we need to first delete everything that we won't be needing. That means deleting all the other kittens. The downloaded file is well organized so we only need to delete all but one layer of the illustration, the one with the cat with the yarn ball will remain. To see the layers we need to go into Window Layers and delete all the layers that we are not using. If you are not sure, toggle the eye button to make certain you are deleting the correct one. And last we need to modify the artboard. We are going to do this using the artboard tool and choosing Fit to Artboard Bounds. Now we move into the second part, apply layer and object names. We need to go back to the layer section and verify that each layer has a unique name and is easy to identify. In this case we will rename our layer cat in lowercase. Depending on the animation, sometimes we need to be very specific and name every part of the illustration. All these names will turn into IDs when we export the file. If we wish to be more specific with this illustration we can apply a name to every part of the cat. For example, ear 1, ear 2, necklace, and so on. Sometimes we also need to group elements and name that group. For example, let's name and group all the elements of our yarn ball. To do this we need to double-click our cat in order to access the main group and zoom into the yarn ball. And using the Shift key and the black arrow we must select all the elements that are part of it. Once we are done selecting them, we right-click into it and select group. At last we name this group yarn ball. Now we are done with preparing our file it's time to export it and optimize it.
Optimize SVG and Animate
Now we have our illustrator file prepared, it's time to export it and optimize it. We don't usually use the SVG file at the exact way that it is exported since a lot of that code is unnecessary for our everyday use. So let's get back on our illustration file. We need to save a copy as SVG. Don't be confused with SVG Compress. Our illustrator will ask us about how we want to export this file. It is important to toggle the More Options view where we will find the most interesting features. When asked about CSS properties we will pick the Presentation Attributes which will apply the style properties in the elements themselves, giving us more flexibility. Okay, now go ahead and open the exported file in a text editor. It has converted all the names we applied to layers to IDs, but it doesn't look that good, does it? Because we still need to optimize it. There are many optimizers out there to choose from. All of these are open source and free to use. SVGOMG by Jake Archibald is my favorite one. Once you upload the file you will be shown your illustration on the left and a list of options on the right. If you are working with a white-looking SVG you will be able to toggle a dark background to work more easily. On the right you will be able to choose if you want your code to look readable or not by using the Pretify Code toggle. If you wish to round numbers or not and for example, if you want to modify IDs. For our cat we will keep it readable code and we will avoid changing the IDs. On the other hand, if your file is not meant for animation then I would recommend to keep your code as small as possible. Now let's click the Download button and let's take a look. Our optimized file looks much cleaner, the IDs are still there, and the code looks readable. Another options it the SVG-Optimizer by Peter Collingridge. This optimizer has fewer options, but it is still a great tool for a quick optimization. We can choose among options such as remove or keep white space, removing unnecessary groups and so on. The last option is SVGO, an optimizer with open UI. It works through npm and will let us optimize SVG by using our terminal. First, we need to install it. We can use our favorite terminal and run npm install -g svgo and then we can compress a file using svgo plus the name of our file. For example, cat .svg. If we wish to create a different file and save it as a copy we will use svgo cat.svg -o cat.min.svg. That will create a new file called cat.min.svg with the compressed code. Among these three I would recommend SVGOMG because of its user interface where we can toggle multiple options and see the results at the same time. Now our code looks a lot better and our cat is still looking great. I must warn you to beware of the optimization because even though it is a necessary tool it can sometimes break our illustration. So be very careful when optimizing and save a copy of your original illustration to avoid any trouble until you are sure that the optimization went great. Okay, it's now time to animate.
Animating SVG with GSAP
Getting to Know GSAP
In this part of the course we will begin working with the GreenSock framework and animating our interfaces with JavaScript. GreenSock is also known as GSAP, short for GreenSock Animation Platform. And it might come as a surprise, but GreenSock was originally built for Adobe Flash a lot of years ago. It used to work as an additional animation tool for Action Script. A lot has happened since then and now GSAP is known as a wonderful tool to animate HTML file interfaces. Because that's basically what GreenSock does today. It animates elements on the web. It doesn't matter if you want to animate a detail or an SVG element. The most wonderful thing about this animation tool is that you no longer need to worry about browser support or different cross-browsers' behaviors. Since GreenSock can actually reach Internet Explorer 7 with animations made on HTML elements and Internet Explorer 9 with SVG animations. And that's the best part of it. You no longer need to worry about the boring stuff and that means that you have more time to let your creativity go wild without limits. So before we get into animating with JavaScript I would like to mention two links. The first one is the official GreenSock forum which is a great place to ask any questions you have. The community there is very nice and big enough to help you solve any issues you find. And the second link I would like to share with you is a showcase of real-life examples that GSAP put together so you can get inspiration and learn how far you can take your animation ideas with this great tool.
Using GreenSock with SVG
Here we are, finally ready to animate. We will be working on a nice spaceship animation using this illustration from freepik.com. We won't be animating the full illustration, only the spaceship. I have created an Adobe illustration file for you to be ready to be exported and an SVG also ready to be animated. So pick the one you prefer from the assets folder. Okay? Let's take a look at the illustration file. This is our spaceship or UFO. I have separated the elements and named a few of them. Since we are not animating each part of this illustration there is no need to apply a name to every element. So far, the layer is called a spaceship and it is divided in two sections, ship and light. Inside the ship group we can find another group called lights with five black circles. Once again we won't be animating the other elements so there is no need to name them, but you can do so if you want to keep everything more organized. I have already exported and optimized my SVG. You can find it in the course assets. As you can see the styles are separated from the elements and everything is easy to identify, thanks to the IDs. Now our SVG is ready, it's time to add GreenSock to our project. We need to go to greensock.com and click the Download button. You can also get them on npm if you prefer that. For this example, we will choose the lightweight version. This is more than enough for most animations. We will talk about the others later on in this course. This is called TweenLite. It's a fast, lightweight, and flexible animation tool that serves as the foundation for the GreenSock Animation Platform. So let's take these CDN links to our HTML page. Now we need to set up a local server because sometimes browsers, especially Chrome, block different external resources for security reasons when we run them as local. There are many ways to get that local server running. If you are using Windows you can try XAMPP or WampServer. Both are free to use. If you are using Linux you can try LAMP server and if you are using macOS there is MAMP server also available. You can also use Node.js to set up a local server. Http-server is a great npm package from that or you can also use Python. Check a few more examples and recommendations on the Mozilla Developer Network website. The next step is to add the SVG we are going to animate to our HTML file. There are two ways of doing this and they will impact how we find our elements. We can add our illustration as an inline SVG. We copy our code directly into our HTML or we can link the file as an external resource using the Iframetag. Let's take a look. If we copy all our SVG documents into our HTML we can select our elements using the most common JavaScript methods such as get element by id or query selector. So let's see if we can select the ship group. We will use a console log to test if everything is working okay. And let's check the browser. There it is. It has returned our element. Now go ahead and try with another part of the illustration. An inline SVG works perfectly, but the HTML might get a little messy over time. That's why an external SVG is a good option as well. So let's try doing the same, selecting the ship but with an external SVG. We load the SVG with an iframe tag and try to get the element with the ship ID, and nope, we get null. This means that we cannot get the elements this way. But fear not! The solution is not difficult. First, we add the DOMContentLoaded event to wait for the document or ship model to be ready and then we add the load addEvent to wait until all assets are fully loaded. Now we need to add an ID to our iframe tag. I will call it illustration. Then we apply content document property to save the document ship model of our external file in a new variable called doc. From then on we can select our elements using our everyday methods like getElementById. It may take a little more code than using an inline SVG, but it will keep your HTML very organized.
TweenLite
Now we know how to select elements, it's time to animate them. We will be working with our previous example of the spaceship loaded in the external file. So what is a tween? It is on a small animation applied to an element. We can define the duration and the different transformations that the elements will have. For example, we could move the elements using the x or y properties or rotate them using rotation and even scale them. Besides, we can change the background colors with height, opacity, and even add our modified box shadows. Remember that to get a good browser performance the best properties to animate are transforms and opacity. There are two ways of animating using TweenLite, from and to. When you use a from animation you are defining where the starting point will be and unless you mention the finishing point, GSAP will take your default values as the end of the animation. This is ideal when you want your elements to make an entrance animation. Let's see an example. I will make the spaceship enter from the left to the starting point. We select the element, save it in the spaceship variable and then tell it to make a tween of 2 seconds from the position of -1000. Now we see how the spaceship enters the screen and it stops when it gets to the starting point. On the other hand, if we use the to animation we are defining how we want our animation to end and the beginning point will be the default values. If we use the to tween we can the spaceship leave the screen. It will take a 2-second animation with an x position of -1000. Now we can see the difference between entering and leaving animations with from and to. GSAP has a few optional values that are great to improve our animations. One of those is the delay. We can add a 4-second delay to our spaceship animation. Let's see. And now it animates. Now these are great, but do you know what's better? Easings. To add a customized easing you can use the ease keyword and pick one from the Ease Visualizer web page. The number of options is unbelievable, especially if you are used to CSS. With GreenSock you can pick any of these and see how they look before applying them to your code. The most common ones are called power. Power0 is a linear easing, which means no acceleration or constant speed. You can choose if you want them as easeOut begins fast and then it slows down. Ease in which means we'll accelerate at the end, or easing out that accelerates in the middle of the animation. There are also bouncing easings available like Back, Elastic and Bounce. And if you don't mind adding an additional JavaScript file you can even create your own custom easing. For our spaceship we will use the Power3 easeinOut. So let's copy this code and take it to our animation. And look at this. It's beautiful! Okay, just one more thing about TweenLite: callbacks. There are a few available like onStart or onComplete and they will let you call any function you want. You can read about them in the TweenLite documentation. So this is the beginning of what the GreenSock platform can do. As you can see, with only a few lines of code and a light library we have great browser support and an amazing customization.
TimelineLite
We move now into the timeline. TimelineLite is a sequencing tool for GreenSock animations. It will let put one animation next to the other. If we wanted to do this with the tools we have right now it would be a little difficult and hard to scale. We will have to create a tween after the other and add a relay to the second animation that equals the duration of the first one. For example, if the first animation has the duration of 2 seconds, the animation that follows will have that delay. This will work, but it's hard to scale. Let's imagine we have this timeline and we begin adding animations one after the other. We change these animations with different delays. But then we realize we forgot to add one animation. Now we need to start again and modify all values that we already had. The truth is tweens are not enough to create chaining animations. We need something that scales easily. That something is called TimelineLite. It will let us chain animations in a simple way, keeping our code dry. So let's get to work. First of all we need to add TimelineLite to our files. Remember we can get it at greensock.com in the Customize tab. And now we create a timeline and save it in a variable. Once we create it we can begin adding tweens using to or from. From now on each tween will play once the previous one has finished. Let's try it with our spaceship. It will begin outside the screen with the next position of -1000. Then it will go to its original position of 0 and finally it will go back the way it came. As you see, we changed these animations without doing any math or counting delays and durations. It works automatically. GreenSock will also let you overlap animations in a timeline. All you need to do is add a negative number after the transforms and and this stream will overlap with the previous one. For example, half a second. You can also do the contrary. Define a value as an additional delay to the next animation. Instead of using a minus you need to write a plus icon. Another interesting feature of GSAP is staggering. This will let us apply a single animation to all elements that share a CSS class for example. And each one of these will have a difference of 0.5 seconds of delay. Let's try this with the lights of our spaceship. Our lights share the same class which is light. So in our JavaScript we will select them all using querySelectorAll. This will create an array of all our elements. Now in our timeline we add the staggerFrom method. We indicate that we want to animate the lights array. The duration will be half a second. We will scale down our elements using a transformOrigin in the center of the lights and also we will change the fill color to yellow. All this will take half a second, but each animation will trigger after 0.2 seconds. It will give us this great effect.
Controls
Now we know how to animate the timeline, it's time to learn how to control it. With GSAP you have absolute control over your animations. You can play them at the right moment, pause them, repeat them, and move them forwards or backwards. First of all we need to pause our animation before we can control it. We will do this by passing paused: true as an option to our timeline when we create it. I have paused the animation and added four buttons, play, pause, seek, and reverse. We have one event listener for each one of them. For the play button we will use the tl.play method. For the pause button the pause one. Seek is a little different. It will move the animation to a point in the timeline, for example 1.2 seconds and then if we want to we can play it from that position. Finally, we have the option to reverse the animation with .reverse.
TweenMax and TimelineMax
The best part about GreenSock is that you only take what you need. If you don't need a timeline you simply load TweenLite and automatically get great results in a performant way. That means you don't need to load the full GSAP library if you are not going to use it. And if you need more features you can use TweenMax and TimelineMax, the most powerful libraries for animations. Both extend the predecessor in different ways. On one hand, TweenMax extends TweenLite with some extra features and the possibility of loading only one file instead of three or four. On the other hand, TimelineMax extends TimelineLite. It will also give us the possibility of loading less files and at the same time we will have more features available. Among those we can find repeating. Just as an example of repeating, let's apply the repeat method to our staggering animation. I have modified the scripts and now we are adding TimelineMax instead of the Lite version. Once we finish our staggering animation we will tell it to repeat a number of times, three for example. If you wish it to repeat indefinitely you need to add -1. I highly recommend you go to greensock.com and read about all the possibilities that these powerful libraries can give us. As a finishing note, let me recommend you what to choose and when. Choose TweenLite for the most simple animations, the ones that don't need a timeline. If you need to chain animations just TimelineLite instead, and if you need repeating features, go for TimelineMax.
Other Animation Libraries
Other Animation Libraries
If we don't fill libraries in JavaScript there are a few libraries out there that will let us animate SVG without too much hassle. I have chosen my two favorites. They are quite different from one another, but that's the idea. They will let you do different things in different ways. First of all, let me introduce you to Vivus.JS. This is a small JavaScript library that will let you animate lines as if someone was drawing them. You can trigger these animations on page load or on a scroll. The library has no dependencies, which makes it really small, but it only has a few options available so if you want to create something crazy, this might not be the library for you. The other library I would like to mention is not really a JavaScript library, but an After Effects extension. It's called BodyMovin. It will turn your animations into code. Recently BodyMovin has joined a project called Lottie by Airbnb. So if you want to go there right now you could find this as Lottie as well. The fact that BodyMovin is the tool to export animation from After Effects makes it a wonderful resource to working teams where there are developers and motion designers.
VivusJS
This small JavaScript library without any dependencies will let us animate SVG strokes. These animations will trigger on page load or when the user scrolls. It features different animation types and easings that you can choose from. There are a few conditions that we must follow for this to work. First, we can only use path elements. We won't be able to animate other tags like circles, rectangles or polygons. And second, we need to use only strokes because that's what Vivus animates. If we accidentally use a fill property it won't work. Another important thing is that the order of the animation is defined by the SVG order. This means the order in which we draw our SVG illustrator. Don't worry if you don't get it right. You can always change the SVG later and modify the order of the elements, and it is also worth mentioning that Vivus.JS takes internal and external files. So we can pick our favorite option. So let's get to work. First, we need to add Vivus.JS to our project. We can find the necessary files on github.com and add them to our HTML. Then we need to export and optimize our SVG. In the course assets you will find this work of art by yours truly, and if we check the SVG, we can see there are no fill properties, only strokes. This will assure us that the animation will go great. Now we create a new element with an id of art and we will define our animation and call our SVG in the script tag using new Vivus. In here we specify the id of our element, art, the duration, and finally the file we want to load. In this case, art.svg. As we can see, it looks great. Duration is defining frames per second. This means that you might never know for sure how long the animation will take since many factors are filling this number, but you could use 45 or 50 frames per second as a reference. There are a few options we can apply to our Vivus animation. For example, the type of animation. The default value is the delay that animates each line with a tiny delay, but we could try oneByOne or sync. Another thing you can do is add a callback function. As you can see, Vivus is a great choice whenever you wish to make this kind of animations with a lightweight library.
BodyMovin
BodyMovin is an After Effects plugin that will export your animations to a JSON format like you can play with our JavaScript player. BodyMovin works great in After Effects. It supports shapes, solids and texts. It also works well with masks, but it doesn't fully support expressions. You can read a little more about expression support on the GitHub page. Most animations will work great without them so you shouldn't worry about that. Using BodyMovin is very simple. First of all you need to add the BodyMovin plugin to After Effects. You can find the plugin on aescripts.com and follow the instructions for the installation. Once you have the plugin, all you need is an After Effects composition. Find one called spaceship in the course assets and open it in After Effects. If this is the first time you used this software this might be a little overwhelming at first, but don't worry. We are not going to try to modify this animation. We are just going to export it. Nevertheless if you do want to learn how everything works, you can find some great After Effects courses here on Pluralsight. Here we have a spaceship animation with some stars. You can play with the spacebar to see how it looks. The animations are simple. The spaceship moves from left to right. It's standing a little longer in the middle and the stars animate some opacity values. So first we need to export the JSON file of these animations. To export the JSON file of our animation we need to go to Window, Extensions, BodyMovin. Here we will select our composition which is called test and define the destination folder. Then we could render. This exports our JSON file. If we open it, it looks like a bunch of letters and numbers, which is cool because that's our great animation. It has also exported the spaceship as an asset inside the Images folder. This isn't ready yet. We need to create our HTML and use the Lottie player to make this JSON work. To get the Lottie player, go again to Window, Extensions, BodyMovin, but this time instead of selecting Render, we will click Get the Player. In here we can choose the gzipped version or the normal one, both will work the same way, and go ahead and pick the first one. Save this file in your Animation folder. And let's finally get to work on the HTML to define our animation. In HTML we will load the Lottie player and create a div element with an id. This will be the place where our animation will render. Now we call lottie.loadAnimation and define the container, our div element. The renderer will be svg. Autoplay will be set to true and the path to the JSON file will be, in my case, data.json. Notice how we don't need to define a duration because it will take the one from the original After Effects composition. Okay? Let's try it. And it looks great and it only took 5 lines of code. We can also define if we want to repeat an animation with the loop option set to true. Now once the animation finishes, it begins again. So as you can see, BodyMovin and Lottie will help us developers and motion designers to work better together and create amazing animated interfaces.
Course author
Eva Ferreira
Eva Ferreira is a freelance Front-End developer with a passion for teaching, currently working on CSSConf Argentina!
Course info
LevelIntermediate
Rating
(13)
My rating
Duration0h 54m
Released9 Jul 2018
Share course