Anime.js to MP4 and GIF with Node.js and FFMPEG

Anime.js to MP4 and GIF with Node.js and FFMPEG

Anime.js to MP4 and GIF with Node.js and FFMPEG

Overview

When it comes to web animations, there are two popular options available: canvas-based animation using pixel-based drawings or CSS-based animation applied on HTML DOM elements.

While canvas animation is often considered the simpler approach for exporting animations to video and GIF formats, it can also limit the range of animations that can be created. Although complex and advanced animations are a possibility, it can quickly become a memory-intensive operation, especially when exporting to popular animation formats.

On the other hand, CSS-based animation tools like anime.js offer a more lightweight yet powerful approach to animation, allowing for more complex and visually engaging animations. With anime.js, you can create animations that manipulate CSS properties like colors, opacity, transforms, and more to achieve a wide range of effects. However, exporting these animations to video and GIF formats on the server side can be a more challenging task due to the complexities of translating the CSS-based animation into an accurate video or GIF output.

What we’re going to build:

In this article, I will provides a detailed and step-by-step instructions to converting anime.js animations from the client-side to MP4 and GIF formats on the server-side. The process involves utilizing a combination of Node.js modules and FFMPEG executable to successfully achieve the conversion.

The process starts by first setting up the project’s base structure and configuring the Node.js environment with the necessary modules. Next, it involves creating an anime.js animation on the client-end, as well as writing a combination of server-side scripts to generate an MP4 video of the animated HTML DOM elements.

Then, by taking it one step further and with minimum of effort, I will demonstrate how you can further enhance the output capabilities by adding an FFMPEG executable in the mix to seamlessly convert the MP4 video output to a GIF file.

Since handling dynamic animations and video generation is normally a resource-intensive process, I will also be mindful that the solutions offered in this guide not only allow for greater flexibility but also optimize the workflow and minimize resource usage.

Setting up the Project:

To get started, let’s set up our project with the necessary dependencies and structure. Express Generator, a widely-used Node.js tool, can help us quickly initialize our project and establish the base.

First install Express Generator globally by running the following command in your terminal:

Then run the following command on the project’s terminal:

This command creates a new directory named “anime.js-to-mp4-gif” with a basic structure for an Express app using the Handlebars (hbs) view engine.

Here’s a possible diagram of the project’s directory structure created by Express Generator:

In this structure, app.js is the main file for our application. The bin/www file is responsible for starting the server. The public directory contains static assets including images, JavaScript, and CSS files. The views folder is from where the templates are loaded from and rendered by our application.

Also make sure to that you have installed the necessary dependencies listed in the package.json file:

Adding Elements

It’s time to start adding elements that we intend to animate. Add the code below to the layout.hbs template file from the /views folder at the root of your project’s directory:

This code snippet sets up the layout structure for the HTML page. In order to style and animate client-side elements, google fonts and anime.js library are imported via link and script tags, respectively, in the head section of our layout.hbs file. The {{{body}}} placeholder in the body section is where the main content of our project’s index.hbs page will be inserted.

Next, add the following code in the index.hbs template file from the views folder:

The index.hbs template file now has a div element with the class name container, which will hold the elements that needs to animate. In this case, there are three elements within the parent div: a div with the class name svg, which contains an SVG icon, followed by two more div elements, with the class name company and slogan respectively.

Finally, in order to ensure that the added elements are visually consistent with the rest of the page, let’s add some CSS in your style.css file located in the /public/stylesheets folder.

The .svg, .company, and .slogan classes are used to position and style the SVG icon, company name, and slogan, respectively. The .container class is used to set the styling for the container that holds the SVG icon and the related text elements in our layout.

Run your project using the command npm start.

 

Launch http://localhost:3000 on your browser to view your page.

Launch http://localhost:3000 on your browser to view your page.

Opting to use a professionally styled logo for our project is to demonstrate that by utilizing the methods discussed here, you can easily export animations of highly aesthetic elements to pixel perfect MP4 and GIF outputs.

Adding Animation

It is time to start applying animation to the existing elements. Create an index.js file in the /public/javascripts folder, which is where the JavaScript code to initiate and control the client-side animation will be placed:

The above code snippet adds the animation to the timeline and initiates the animation sequence when the DOMContentLoaded event is fired. This ensures that the animation is only initiated once the relevant elements are available in the DOM.

An anime.timeline object is initiated with the loop property set to false and the autoplay to true. Next, a function initiate is defined responsible for handling the individual animations to the timeline. Finally, a timeline.add method is used to add the animations.

Breakdown:

  • The first animation targets the .svg element and scales it from 0 to 1 while also increasing its opacity. The easing function used is easeOutExpo, and the duration is set to 1500 milliseconds.
  • The second animation targets the .company text element and translates it from -150px to 0px on the X-axis while also increasing its opacity. The duration is set to 2000 milliseconds.
  • The third animation targets the .slogan , also a text element, and translates it from 50px to 0px on the Y-axis while also increasing its opacity. The duration is set to 1000 milliseconds.

Next, the initiate function is invoked to start the animation sequence.

Import the index.js file in our index.hbs template.

Reload the page to see the animation in action!

Reload the page to see the animation in action!

In the next step, I will demonstrate the significance of keeping our animation code within the initiate function and how it ensures an accurate transition of capturing and posting the animation data to the server-side for conversion.

Exporting to Server-side API

Until this point, we have established the project, created the DOM elements, and implemented animations. While these tasks are significant, they are relatively straightforward compared to the upcoming critical steps. We have now reached the core of the process that directly impacts the end result.

As I mentioned earlier in this article, handling dynamic animations and video generation can be a resource-intensive operation. Therefore, it is also crucial to opt for an approach that is minimalist in nature and helps optimize the workflow.

Add the following code snippet to the index.js file:

A convert function is defined, along with an object data with a following set of parameters:

Breakdown:

  • The html parameter uses document.querySelectorAll to store the entire HTML content of the container element withholding the animated objects, including the parent element itself.
  • Since initiate is a function that contains the animation timeline, toLocaleString() is used to convert the initiate function to a string so that it can be included in the animation parameter being sent to the server.
  • The duration parameter is being set to the duration of the animation timeline created using anime.js. The timeline duration is measured in milliseconds, but the server-side conversion expects the duration to be provided in seconds. Hence, the duration value is divided by 1000 and converted to a number using the Number() method.
  • The width parameter is being set to the width of the container element. The offsetWidth property is used to retrieve the width of the element in pixels.
  • For the height parameter, similar to it’s offsetWidth counterpart, the offsetHeight property is used to retrieve the height of the container element in pixels.

Including the aforementioned parameters in the data object ensures that the server API receives the accurate animation data required to convert the animation to MP4 and GIF formats. Moreover, utilizing JavaScript’s toLocaleString() method to stringify the initiate function also keeps the payload greatly reduced to achieve faster load times and improved overall performance.

Next, the data object is passed as the body of the request, and sent as a POST request to a /convert-to-video endpoint by utilizing a fetch API.

Finally, let’s bind the convert function to the onclick event of the submit button.

The Conversion Process

  • Creating the videoRouter:

To handle the POST request sent from the client, a new route in our server-side code needs to be created. This route will receive the animation data sent from the fetch api and process it for conversion.

Open the app.js file from the project’s root directory and add the following code:

Your app.js should now look like this.

Creating the videoRouter route allows us to handle requests at the root endpoint. Next, create a video.js file in the routes directory of our project.

Our videoRouter route now listens for a POST request at the /convert-to-video endpoint. It also retrieves the animation data sent in the request body using the req.body object.

  • Replicating the Animation on Server-side:

To create a precise MP4 version of our animation, the server-side scripts will need to be served with an identical copy of our client-side animated DOM elements and structure. This is where toHTML.js module comes into play, ensuring that animated DOM elements are duplicated and saved on the server-side as an HTML file.

Starting by create a new folder called modules at the root of our project where all the server-side code conversion will be stored. Next, create your first module, toHTML.js, inside the modules folder with the following code:

The toHTML module takes in parameters data.html and data.animation, containing the animated DOM element’s HTML markup and the initiate function code in an stringify form respectively. By utilizing these params, toHTML module is able to generate an HTML code similar to the one created on the client, and then write it to an HTML file called animation.html in the /public/output folder of the project.

We now have a file that will enable us to replicate the animation on the server-side. If you open the server-side generated animation.html in your browser, it will play the exact same animation as created on the client end.

Here’s the code of the generated animation.html file for a quick comparison:

By drawing parallels in terms of code structure to the client side equivalent of our generated animation.html file, you will find that there are only a few minor differences such as the animation script is now inline, and the body margin set to zero to avoid any unwanted margins in the output. Additionally, the timeline is declared with its scope set to global to avoid code breaks since it was defined outside the scope of the original initiate function.

Next, call toHTML module inside the video.js route file:

Our server-side is now ready to proceed with the conversion process.

  • Conversion to MP4 using timecut:

The timecut module of Node.js is specifically developed to capture videos of web pages that use JavaScript animations with smooth transitions. It works by opening the web page, replacing its time-handling functions, taking snapshots of the page, and sending the results to FFMPEG for encoding the frames into a video. This process enables high-fps capture of frames, ensuring that the resulting videos have smooth transitions.

Install timecut to our project by running the following command:

Then create a folder called “ffmpeg” at the root of our project and place the ffmpeg executable file in it.

Note: To download the ffmpeg executable for your preferred operating system, you can visit its official website at https://ffmpeg.org/download.html.

Next, create a toMP.js module file inside the modules folder, containing the script to perform the MP4 conversion using the timecut module:

Breakdown

  • The toMP4 module takes in the data object as input, which contains the width, height, and duration of the animation.
  • The timecut function captures the animation from the animation.html file. The viewport object is used to set the width and height of the captured video. The selector specifies the container element that contains the animation. The fps option sets the frames per second of the resulting video, and the duration option specifies the duration of the video in seconds.
  • The launchArguments option is used to pass additional arguments to the browser instance, and the output option specifies the output file path for the MP4 file.
  • The ffmpegPath option specifies the path to the ffmpeg executable file downloaded earlier, and is used to encode the captured frames into an MP4 video.

This part of the process is comparatively straightforward since all that needs to be done is to serve the server-side animation.html file to the timecut module along with few other essential parameters and timecut will take care of the rest.

To ensure that the MP4 starts generating only when the animation.html is successfully created, call the toMP4 below the toHTML module:

Post your animation data and initiate the server-side process by clicking the convert button.

Frame by frame conversion in real-time in the terminal of your project.

Frame by frame conversion in real-time in the terminal of your project.

Our animation is around 4.5 seconds long, hence, at a frame rate of 30 fps, it will produce a total of 135 frames. These frames will be converted into an animation.mp4 file and saved in the /public/outputfolder using FFMPEG executable.

The view of the generated MP4 video

The view of the generated MP4 video

  • Conversion to GIF with FFMPEG

Since we already have the MP4 file, generating a GIF version of the same becomes a straightforward process that involves running couple of FFMPEG commands.

Please bear in mind that the FFMPEG library needs to first generate a palette file that will be used to create the GIF output. The palette file is an essential prerequisite used by FFMPEG to map colors in the video to colors in the GIF.

In order to achieve that, first create a toPalette.js module file inside the modules folder.

The FFMPEG command in the code takes the MP4 file as input and applies the “palettegen” filter to generate the palette file. The filter analyzes the colors in the MP4 file and creates a palette file that maps these colors to a smaller set of colors that can be used in the GIF. The resulting palette file is saved as a PNG file in the /public/output folder.

It’s worth noting that FFMPEG needs to create a palette file before creating a GIF file because GIFs are limited to 256 colors. FFMPEG generates a palette file from the MP4 output that contains the 256 most used colors in the animation. This palette file is then used to map the colors in the MP4 output to the 256 colors available in the GIF format.

Our final step is to create a module file called toGif.js, also placed inside the modules folder:

This file exports a function containing the child_process module to execute an FFMPEG command. This command uses the palette file created in the previous step to generate a GIF file from the MP4 output.

Lastly, make sure that both toPalette and toGif modules are executed only when the MP4 is successfully generated:

Application Flow in Nutshell:

To provide better understanding, the following diagram presents the data flow and processes involved in exporting anime.js animations to MP4 and GIF formats on the server-side, utilizing Node.js modules and FFMPEG.

Conclusion

This article offers a complete walkthrough on how to export client-side anime.js animations to MP4 and GIF formats using a combination of Node.js modules and FFMPEG on the server-side. By following the steps discussed, you can develop dynamic and cutting-edge online animation tools with the capabilities to export to both video and GIF formats.

Download

Resources

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

Profiling Tools and Techniques for Node.js Applications

A well-optimized Node.js application not only ensures a smoother user experience but also scales effectively to meet ...

Mastering JavaScript Proxies: Practical Use Cases and Real-World Applications

This article will briefly revisit the concept of JavaScript Proxies and their purpose. We will then dive into a series of practical use cases, ...

Securing Node.js Applications with JWT and Passport.js

JSON Web Tokens (JWT) is a compact and self-contained technique for securely transferring data between parties as a JSON object is defined by the ...

No comments yet

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy