search
HomeWeb Front-endJS TutorialHow to Create Animated GIFs from GSAP Animations

Convert GSAP animations to animated GIFs: a step-by-step guide to using modern-gifs

Key Points

  • You can use a process to convert GSAP animations into animated GIFs that involve capturing SVG data and writing them to the HTML canvas every time you adjust the tween. This SVG data can then be converted into rasterized image data, which is then used by modern-gif to create each frame of the animated GIF.
  • The conversion process involves multiple steps, including capturing SVG data, converting SVG data into rasterized data, and finally converting the rasterized data into GIF. Each step involves specific code modifications and the use of arrays to store captured and transformed data.
  • Because the frame rates between browser animations and GIFs are usually different, the frame rates of the final GIFs may be slower than the original animation. To speed up GIFs, you can use array filters and JavaScript remainder operators to determine whether the index can be divisible by a number, thus discarding some frames.

This article explains how to convert animations created using GSAP into animated GIFs using modern-gif.

The following is a preview of an animation I made before:

How to Create Animated GIFs from GSAP Animations

In the link below, you can find a live preview of all the code you will refer to in this article:

  • ? Preview:
    • Index: gsap-animation-to-gif.netlify.app
    • Simple version: gsap-animation-to-gif.netlify.app/simple
  • ⚙️ Code base: github.com/PaulieScanlon/gsap-animation-to-gif

There are two "pages" in the code base. index contains all the code for the GIF above, simple is the starting point for the steps described in this article.

How to convert GSAP animation to GIF

The method I use to convert GSAP animations to GIFs involves capturing SVG data and writing it to an HTML canvas at each "update" of the tween. Once the tween is done, I can convert the SVG data into rasterized image data, which modern-gif can use to create every frame of an animated GIF.

Beginner

This is the code I used in my simple example, and I will use it to explain each step required to create an animated GIF from a GSAP animation:

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='utf-8' />
  <title>Simple</title>
</head>
<body>
  <main>
    <svg id='svg'
      xmlns='http://www.w3.org/2000/svg'
      viewBox='0 0 400 200'
      width={400}
      height={200}
      style={{ border: '1px solid red' }}
    >
      <rect id='rect' x='0' y='75' width='50' height='50' fill='red'></rect>
    </svg>
    <canvas id='canvas' style={{ border: '1px solid blue' }} width={400} height={200}></canvas>
    <img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/article/000/000/000/173898187373194.jpg?x-oss-process=image/resize,p_40"  class="lazy" alt="How to Create Animated GIFs from GSAP Animations " /></p>
<h2 id="将-SVG-数据转换为光栅化数据">将 SVG 数据转换为光栅化数据</h2>
<pre class="brush:php;toolbar:false"><code class="language-javascript">gsap.timeline({
  onUpdate: () => {
    const xml = new XMLSerializer().serializeToString(svg);
    const src = `data:image/svg+xml;base64,${btoa(xml)}`;
    animationFrames.push(src);
  },
  onComplete: () => {
    let inc = 0;
    const renderSvgDataToCanvas = () => {
      const virtualImage = new Image();
      virtualImage.src = animationFrames[inc];
      virtualImage.onload = () => {
        ctx.clearRect(0, 0, 400, 200);
        ctx.drawImage(virtualImage, 0, 0, 400, 200);
        canvasFrames.push(canvas.toDataURL('image/jpeg'));
        inc++;
        if (inc < animationFrames.length) {
          renderSvgDataToCanvas();
        } else {
          //console.log(canvasFrames); //调试用
          generateGif();
        }
      };
    };
    renderSvgDataToCanvas();
  },
})
.fromTo('#rect', { x: -50 }, { duration: 2, x: 350, ease: 'power.ease2' });

This step is a little more complicated and requires one operation on each index of the animationFrames array.

By using the recursive function renderSvgDataToCanvas, I can use the image data in the animationFrames array to write it to the canvas. Then, by using canvas.toDataURL('image/jpeg'), I can store the rasterized data of each frame of the animation in the canvasFrames array.

If you have added console.log in the onComplete function, you should see something similar to the following in the browser console. However, this time note the MIME type of the data: it is not svg xml, but image/jpeg. This is important for the next work I will do.

How to Create Animated GIFs from GSAP Animations

Convert rasterized data to GIF

This is the last step, which involves passing each index of the canvasFrames array to a modern-gif.

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='utf-8' />
  <title>Simple</title>
</head>
<body>
  <main>
    <svg id='svg'
      xmlns='http://www.w3.org/2000/svg'
      viewBox='0 0 400 200'
      width={400}
      height={200}
      style={{ border: '1px solid red' }}
    >
      <rect id='rect' x='0' y='75' width='50' height='50' fill='red'></rect>
    </svg>
    <canvas id='canvas' style={{ border: '1px solid blue' }} width={400} height={200}></canvas>
    <img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/article/000/000/000/173898187373194.jpg?x-oss-process=image/resize,p_40"  class="lazy" alt="How to Create Animated GIFs from GSAP Animations " /></p>
<h2 id="将-SVG-数据转换为光栅化数据">将 SVG 数据转换为光栅化数据</h2>
<pre class="brush:php;toolbar:false"><code class="language-javascript">gsap.timeline({
  onUpdate: () => {
    const xml = new XMLSerializer().serializeToString(svg);
    const src = `data:image/svg+xml;base64,${btoa(xml)}`;
    animationFrames.push(src);
  },
  onComplete: () => {
    let inc = 0;
    const renderSvgDataToCanvas = () => {
      const virtualImage = new Image();
      virtualImage.src = animationFrames[inc];
      virtualImage.onload = () => {
        ctx.clearRect(0, 0, 400, 200);
        ctx.drawImage(virtualImage, 0, 0, 400, 200);
        canvasFrames.push(canvas.toDataURL('image/jpeg'));
        inc++;
        if (inc < animationFrames.length) {
          renderSvgDataToCanvas();
        } else {
          //console.log(canvasFrames); //调试用
          generateGif();
        }
      };
    };
    renderSvgDataToCanvas();
  },
})
.fromTo('#rect', { x: -50 }, { duration: 2, x: 350, ease: 'power.ease2' });

Using modernGif.encode, you can pass an array of data to frames and define a delay for each frame, I chose to add a delay of 0 seconds.

The next part of the

code handles converting modernGif.ecode data and converting it to "another" MIME type, this time image/gif.

Once I have the final "blob" data representing an animated GIF, I convert it to a URL and then set the src and href of the image and link elements so that I can view and download the GIF in my browser.

How to Create Animated GIFs from GSAP Animations

Frame rate

You may notice that the final GIF runs quite slowly, because animations running in the browser usually play 60 frames per second (fps) while GIFs are usually much slower at 12 or 24 fps.

To "discard" some animation frames, I use array filters and JavaScript remainder operators to determine if the index can be divisible by a certain number, in my case, I choose 6. Indexes that cannot be divisible by 6 will be filtered out from the array. The generated animated GIF is a bit clumsy, but it plays much faster.

I have added the generateGif method to the filter function to implement the adjustment of the frame rate.

That's it, you can convert GSAP SVG animations to animated GIFs via HTML canvas!

If you have any questions about anything described in this article, feel free to find me on Twitter/X: @PaulieScanlon.

The above is the detailed content of How to Create Animated GIFs from GSAP Animations. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.