Home > Web Front-end > JS Tutorial > How to Create Animated GIFs from GSAP Animations

How to Create Animated GIFs from GSAP Animations

Christopher Nolan
Release: 2025-02-08 10:31:09
Original
411 people have browsed it

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="https://img.php.cn/upload/article/000/000/000/173898187373194.jpg" alt="How to Create Animated GIFs from GSAP Animations " /></p>
<h2>将 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' });
Copy after login
Copy after login

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="https://img.php.cn/upload/article/000/000/000/173898187373194.jpg" alt="How to Create Animated GIFs from GSAP Animations " /></p>
<h2>将 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' });
Copy after login
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template