Learn · Developers

How to convert an animated SVG to MP4 or GIF with Python

Contents

An animated SVG is a few kilobytes of text that plays in any browser: a logo that draws itself, a loading spinner, a check mark that pops in.

The trouble starts when it has to go somewhere that isn’t a web page. A social post, an ad slot, a slide deck and a video edit all want a video file or a GIF.

GIF is still a large part of the web’s images. The 2024 Web Almanac counted the image formats on more than 10 million pages: “JPEG comes in first, at 32.4%. Next, we have PNG, at 28.4%, GIF, at 16.8%, WebP at 12%, SVG, at 6.4%”.

You could record your screen while the SVG plays, but a recording drops frames and comes out a little different every time.

This guide converts the SVG to MP4 or GIF with Python and Shotstack’s video editing API instead. The API renders the animation frame by frame, so every frame is exact. One script converts a single file, and a second one converts a whole folder.

TL;DR

  • Put the SVG markup in an html5 clip. The renderer plays the SVG in a real browser and captures every frame at its exact time.
  • CSS animations inside the SVG render as they are. A 2.6 second logo animation became a 2.6 second MP4 of 65 frames at 25 fps.
  • Set the output format to gif for a GIF. Use 25 fps so the GIF plays at the right speed.
  • SVGs animated with SMIL tags such as <animate> don’t render in step. Rewrite them as CSS keyframes first.
  • For a set of icons or logos, a second script converts every SVG in a folder to MP4 and GIF in one run.

What you need

  • A Shotstack API key. Sign up for free and copy the production key from the dashboard. Production renders use credits (see pricing).
  • Python 3.9 or later. The scripts don’t need any packages.
  • An SVG file that is animated with CSS and has a viewBox.

Set the key in your terminal before you run anything:

Bash
export SHOTSTACK_API_KEY="your_production_key"

How an animated SVG becomes a video

A Shotstack edit is a JSON timeline of clips. One clip type, html5, takes a web page as three strings (html, css and js) and renders it as video. A web page can hold an SVG inline, so the whole file goes into the html string as it is.

The renderer doesn’t play the page in real time. It moves every animation to the time of each frame, captures the frame, then moves on. Our guide to converting an HTML animation to MP4 explains this in detail, and the HTML5 docs list what the renderer can drive.

For an SVG, it comes down to how the file is animated:

How the SVG is animatedWhat to do
CSS @keyframes or transitions in a <style> blockNothing. It renders as it is.
A JavaScript library such as GSAPPut the script in the js string (see the FAQs).
SMIL tags: <animate>, <animateTransform>, <animateMotion>Rewrite them as CSS keyframes (shown below).

Convert an SVG to MP4 with Python

The example is a logo for Fernway, a made-up brand. A ring draws itself, a leaf grows inside it, the name fades up and a line draws under it. Save it as svg/logo.svg:

xml
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 360" width="640" height="360">
  <style>
    .ring { fill: none; stroke: #1f3a30; stroke-width: 10; stroke-linecap: round;
            stroke-dasharray: 440; stroke-dashoffset: 440;
            animation: draw 1.2s ease-out forwards; }
    .leaf { fill: #25d0cd; transform-box: fill-box; transform-origin: 50% 100%;
            transform: scale(0); animation: grow 0.6s ease-out 0.9s forwards; }
    .word { font: 700 56px Arial, Helvetica, sans-serif; fill: #1f3a30; opacity: 0;
            animation: rise 0.7s ease-out 1.4s forwards; }
    .line { stroke: #f2c14e; stroke-width: 6; stroke-linecap: round;
            stroke-dasharray: 250; stroke-dashoffset: 250;
            animation: draw 0.6s ease-out 2s forwards; }
    @keyframes draw { to { stroke-dashoffset: 0; } }
    @keyframes grow { to { transform: scale(1); } }
    @keyframes rise { from { opacity: 0; transform: translateY(16px); }
                      to { opacity: 1; transform: translateY(0); } }
  </style>
  <circle class="ring" cx="150" cy="180" r="70" transform="rotate(-90 150 180)"/>
  <path class="leaf" d="M150 222 C112 190 122 146 150 126 C178 146 188 190 150 222 Z"/>
  <text class="word" x="252" y="196">Fernway</text>
  <line class="line" x1="254" y1="222" x2="504" y2="222"/>
</svg>

Save this script as convert_svg.py, next to the svg folder:

Python
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

API = "https://api.shotstack.io/edit/v1"
SOURCE = "svg/logo.svg"
FORMAT = "mp4"  # "mp4" or "gif"
WIDTH = 1280  # output width in pixels; the height follows the shape of the SVG
LENGTH = None  # seconds; None reads the longest animation in the SVG's CSS
FPS = 25
BACKGROUND = "#ffffff"


def call(url, body=None):
    data = json.dumps(body).encode() if body is not None else None
    headers = {
        "x-api-key": os.environ["SHOTSTACK_API_KEY"],
        "Content-Type": "application/json",
    }
    try:
        request = urllib.request.Request(url, data, headers)
        with urllib.request.urlopen(request) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        sys.exit(f"HTTP {error.code}: {' '.join(error.read().decode().split())[:300]}")


def animation_length(svg):
    """Longest duration plus delay of the CSS animations in the SVG, in seconds."""
    longest = 0
    for declaration in re.findall(r"animation\s*:\s*([^;}]+)", svg):
        times = re.findall(r"(?<![\w.#-])(\d*\.?\d+)(ms|s)\b", declaration)
        seconds = [float(n) / (1000 if unit == "ms" else 1) for n, unit in times]
        longest = max(longest, sum(seconds[:2]))
    return longest


def build_edit(path):
    svg = Path(path).read_text(encoding="utf-8")
    svg = svg[svg.index("<svg") :]
    box = re.search(r'viewBox="([^"]+)"', svg)
    if not box:
        sys.exit(f"{path} has no viewBox")
    box_width, box_height = [
        float(n) for n in box.group(1).replace(",", " ").split()[2:]
    ]
    height = round(WIDTH * box_height / box_width / 2) * 2
    length = LENGTH or animation_length(svg)
    if not length:
        sys.exit(f"No CSS animation found in {path}. Set LENGTH.")
    css = (
        f"html, body {{ margin: 0; width: {WIDTH}px; height: {height}px;"
        f" overflow: hidden; background: {BACKGROUND}; }}"
        f" svg {{ display: block; width: {WIDTH}px; height: {height}px; }}"
    )
    clip = {
        "asset": {"type": "html5", "html": svg, "css": css},
        "start": 0,
        "length": length,
        "width": WIDTH,
        "height": height,
    }
    output = {"format": FORMAT, "size": {"width": WIDTH, "height": height}, "fps": FPS}
    if FORMAT == "gif":
        output["repeat"] = True
    return {"timeline": {"tracks": [{"clips": [clip]}]}, "output": output}


if __name__ == "__main__":
    if not os.environ.get("SHOTSTACK_API_KEY"):
        sys.exit("Set SHOTSTACK_API_KEY first.")
    edit = build_edit(SOURCE)
    size = edit["output"]["size"]
    seconds = edit["timeline"]["tracks"][0]["clips"][0]["length"]
    print(f"{SOURCE}: {size['width']} x {size['height']}, {seconds} s at {FPS} fps")
    render_id = call(f"{API}/render", edit)["response"]["id"]
    print("Render queued:", render_id)
    while True:
        time.sleep(5)
        status = call(f"{API}/render/{render_id}")["response"]
        if status["status"] == "done":
            break
        if status["status"] == "failed":
            sys.exit(f"Render failed: {status.get('error')}")
    print(f"{FORMAT.upper()}: {status['duration']} s")
    print(status["url"])

Run it:

Bash
python convert_svg.py

The script prints the size and length it worked out, then the link to the MP4:

Text
svg/logo.svg: 1280 x 720, 2.6 s at 25 fps
Render queued: 556086ae-0590-456c-ab17-6f1292a0b41a
MP4: 2.6 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/556086ae-0590-456c-ab17-6f1292a0b41a.mp4

Here is the MP4 from that run:

The file is 1280 x 720 and has 65 frames, which is 2.6 seconds at 25 fps.

How the script works

  • Size. The script reads the SVG’s viewBox and keeps its shape. You set WIDTH, and the height follows. A 640 x 360 viewBox at a width of 1280 gives a 1280 x 720 video. The SVG is vector art, so it stays sharp at any size.
  • Length. animation_length reads every animation line in the SVG’s CSS and adds the duration to the delay. The longest one is the length of the video. In the logo, the last animation runs for 0.6 seconds after a 2 second delay, so the video is 2.6 seconds long. Set LENGTH to choose the length yourself.
  • The page. The CSS pins the page to the size of the clip in pixels and sets the background color.
  • The output. output.size matches the clip, and output.fps sets the frame rate.

Make a GIF instead of an MP4

Change two settings at the top of the script:

Python
FORMAT = "gif"
WIDTH = 640

The script adds "repeat": true to the output, so the GIF loops. This is the logo as a 640 x 360 GIF:

A logo animation converted from an SVG to a looping GIF

Keep FPS at 25 for a GIF. A GIF can’t store any frame rate you like. The GIF89a specification stores the time between frames as a whole number of hundredths of a second:

Delay Time - If not 0, this field specifies the number of hundredths (1/100) of a second to wait before continuing with the processing of the Data Stream.

At 25 fps each frame lasts exactly 4 hundredths of a second. At 15 fps a frame should last 6.67 hundredths, which a GIF can’t store. When I rendered the logo as a GIF at 15 fps, the 2.6 second animation played in 2.34 seconds. At 25 fps it played in 2.6 seconds.

A GIF is also much larger than an MP4. The 640 x 360 GIF of the logo is 620 KB. The 1280 x 720 MP4 of the same animation is 77 KB. Make a GIF when the place you’re posting to needs one, and keep its width small.

Loop a spinner without a jump

A spinner animates forever, so there is no natural end to the video. The trick is to render exactly one cycle. animation_length already does this: for an animation that repeats, it returns the length of one turn.

This spinner turns once every 1.2 seconds:

xml
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" width="120" height="120">
  <style>
    .track { fill: none; stroke: #e3e7ea; stroke-width: 10; }
    .arc { fill: none; stroke: #25d0cd; stroke-width: 10; stroke-linecap: round;
           stroke-dasharray: 80 203; transform-origin: 60px 60px;
           animation: spin 1.2s linear infinite; }
    @keyframes spin { to { transform: rotate(360deg); } }
  </style>
  <circle class="track" cx="60" cy="60" r="45"/>
  <circle class="arc" cx="60" cy="60" r="45"/>
</svg>

With SOURCE = "svg/spinner.svg" and FORMAT = "gif", the script makes a 1.2 second GIF of 30 frames. The last frame is one step before the first, so the loop has no jump:

A loading spinner converted from an SVG to a GIF that loops without a jump

To check that the loop holds over time, I rendered two cycles as one 2.4 second MP4. Frame 30, the start of the second cycle, matched frame 0.

Rewrite SMIL animations as CSS

Some SVGs are animated with SMIL, the animation tags that are part of SVG itself. This is the same spinner written with an <animateTransform> tag:

xml
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" width="120" height="120">
  <circle cx="60" cy="60" r="45" fill="none" stroke="#e3e7ea" stroke-width="10"/>
  <circle cx="60" cy="60" r="45" fill="none" stroke="#25d0cd" stroke-width="10"
          stroke-linecap="round" stroke-dasharray="80 203">
    <animateTransform attributeName="transform" type="rotate" from="0 60 60" to="360 60 60"
                      dur="1.2s" repeatCount="indefinite"/>
  </circle>
</svg>

SMIL isn’t one of the animation types the renderer drives, so the frames don’t follow the animation. In my render of this file, the picture changed in only 4 of the 59 steps between frames. The CSS version changed in all 59.

The fix is to move each SMIL tag into CSS. For a rotation it takes three steps:

  1. Delete the <animateTransform> tag and give the element a class.
  2. Set transform-origin to the point the SMIL tag rotated around (60 60 becomes 60px 60px).
  3. Add an animation with the same duration, and a @keyframes rule that ends at rotate(360deg).

The result is the CSS spinner from the section above. Other SMIL tags move over the same way:

SMILCSS
<animate attributeName="opacity">A keyframe on opacity
<animate attributeName="stroke-dashoffset">A keyframe on stroke-dashoffset
<animateTransform type="rotate">A keyframe on transform: rotate() with transform-origin
<animateMotion path="...">offset-path: path("...") and a keyframe on offset-distance
repeatCount="indefinite"infinite

I tested offset-path and the steps() timing function in the same way, and both rendered frame by frame.

Play the SVG over footage

An animated SVG doesn’t have to be a video on its own. It can also sit on top of footage, like a badge, a lower third or a logo sting. The page of an html5 clip is transparent unless you give it a background, so the SVG only needs a video on the track below it.

Save this as overlay_svg.py, next to convert_svg.py. It plays the check mark from svg/check.svg in the corner of a clip:

xml
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width="200" height="200">
  <style>
    .disc { fill: #1f3a30; transform-origin: 100px 100px; transform: scale(0);
            animation: pop 0.5s cubic-bezier(0.2, 1.4, 0.4, 1) forwards; }
    .tick { fill: none; stroke: #ffffff; stroke-width: 14; stroke-linecap: round;
            stroke-linejoin: round; stroke-dasharray: 130; stroke-dashoffset: 130;
            animation: draw 0.5s ease-out 0.5s forwards; }
    @keyframes pop { to { transform: scale(1); } }
    @keyframes draw { to { stroke-dashoffset: 0; } }
  </style>
  <circle class="disc" cx="100" cy="100" r="80"/>
  <path class="tick" d="M62 104 L90 130 L140 74"/>
</svg>
Python
"""Play an animated SVG over footage: a transparent SVG clip on a track above a video."""

import os
import sys
import time

import convert_svg

FOOTAGE = "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/footage/skier.mp4"

if not os.environ.get("SHOTSTACK_API_KEY"):
    sys.exit("Set SHOTSTACK_API_KEY first.")
convert_svg.WIDTH = 240  # the size of the SVG on the video, in pixels
convert_svg.LENGTH = 3
convert_svg.BACKGROUND = "transparent"
edit = convert_svg.build_edit("svg/check.svg")
badge = edit["timeline"]["tracks"][0]["clips"][0]
badge["position"] = "bottomRight"
badge["offset"] = {"x": -0.04, "y": 0.06}
video = {"type": "video", "src": FOOTAGE, "volume": 0}
edit["timeline"]["tracks"].append(
    {"clips": [{"asset": video, "start": 0, "length": 3}]}
)
edit["output"]["size"] = {"width": 1280, "height": 720}

render_id = convert_svg.call(f"{convert_svg.API}/render", edit)["response"]["id"]
print("Render queued:", render_id)
while True:
    time.sleep(5)
    status = convert_svg.call(f"{convert_svg.API}/render/{render_id}")["response"]
    if status["status"] == "done":
        break
    if status["status"] == "failed":
        sys.exit(f"Render failed: {status.get('error')}")
print(f"MP4: {status['duration']} s")
print(status["url"])
Text
Render queued: 0896d124-b17b-416c-ac75-2f66f2bf284d
MP4: 3 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/0896d124-b17b-416c-ac75-2f66f2bf284d.mp4

The script sets the background to transparent, makes the SVG clip 240 pixels wide and moves it to the bottom right with position and offset. The positioning guide covers both settings.

Convert a folder of SVGs

A design system rarely has one animated SVG. It has a set: icons, loaders, a logo in a few versions. This script converts every SVG in a folder to an MP4 and a GIF in one run.

Save it as convert_folder.py, next to convert_svg.py:

Python
"""Convert every animated SVG in a folder to MP4 and GIF with the Shotstack API."""

import os
import sys
import time
import urllib.request
from pathlib import Path

import convert_svg

FOLDER = Path("svg")
OUT = Path("converted")
WIDTHS = {"mp4": 1280, "gif": 480}  # output width in pixels for each format

if not os.environ.get("SHOTSTACK_API_KEY"):
    sys.exit("Set SHOTSTACK_API_KEY first.")
renders = {}
for path in sorted(FOLDER.glob("*.svg")):
    if not convert_svg.animation_length(path.read_text(encoding="utf-8")):
        print(f"{path.name}: no CSS animation found, skipped")
        continue
    for file_format, width in WIDTHS.items():
        convert_svg.FORMAT, convert_svg.WIDTH = file_format, width
        edit = convert_svg.build_edit(path)
        response = convert_svg.call(f"{convert_svg.API}/render", edit)
        renders[response["response"]["id"]] = f"{path.stem}.{file_format}"
print(f"Queued {len(renders)} renders")
OUT.mkdir(exist_ok=True)
while renders:
    time.sleep(5)
    for render_id in list(renders):
        status = convert_svg.call(f"{convert_svg.API}/render/{render_id}")["response"]
        if status["status"] == "failed":
            print(f"{renders.pop(render_id)}: failed, {status.get('error')}")
        elif status["status"] == "done":
            name = renders.pop(render_id)
            urllib.request.urlretrieve(status["url"], OUT / name)
            size = (OUT / name).stat().st_size / 1000
            print(f"{name}: {status['duration']} s, {size:.0f} KB")

Run it on the svg folder, which now holds the logo, the two spinners and the check mark:

Text
spinner-smil.svg: no CSS animation found, skipped
Queued 6 renders
check.mp4: 1 s, 63 KB
check.gif: 1 s, 360 KB
logo.mp4: 2.6 s, 77 KB
logo.gif: 2.6 s, 441 KB
spinner.mp4: 1.2 s, 72 KB
spinner.gif: 1.2 s, 438 KB

The script reads each file’s own size and length, so a square 1 second icon and a wide 2.6 second logo go through the same loop. It skips the SMIL spinner, because it finds no CSS animation in it. That message is the list of files to rewrite. Every result is saved in the converted folder.

These are the three MP4 files from that run:

To keep a larger set in sync, send the files to your own storage as they render. Add a destinations entry to the output, and each file is copied to your bucket when its render finishes. The S3 destination guide shows the settings.

Can FFmpeg convert an animated SVG?

Not on its own. FFmpeg reads SVG through an optional library. Its build script describes the option as “enable SVG rasterization via librsvg”, and the option is off by default. The FFmpeg 8.1 build on my computer doesn’t include it, so ffmpeg -i svg/logo.svg logo.mp4 stopped with “no decoder found for: svg”.

A build that includes librsvg gets you a still picture, not the animation. The librsvg documentation says so in one line: “Animation, interactivity, and scripting are not supported.”

FFmpeg is still a good tool once you have a video. Our guide to converting video to GIF with FFmpeg, for example, starts from an MP4 like the one above.

Turn your SVG animations into video with Shotstack

You now have three short scripts. One converts an animated SVG to an MP4 or a GIF with every frame exact, one plays an SVG over footage, and one converts a whole folder. None of them needs a browser, a screen recorder or an encoder on your computer.

Sign up for a free Shotstack API key and convert your first SVG.

Frequently asked questions (FAQs)

Can I convert an SVG that is animated with GSAP?

Yes. Put the SVG in the html string and the GSAP code in the js string of the html5 asset. GSAP is already loaded on the page, with its DrawSVG and MorphSVG plugins, so don’t add a script tag for it.

Build one timeline and add every tween to it. I rendered a path drawn with DrawSVG and a square morphed into a triangle with MorphSVG, and both moved in every frame.

How large can the video or GIF be?

The limits page gives the sizes: up to 3840 pixels on each side for a video and 1920 pixels for a GIF. An SVG scales without loss, so one file can become a small GIF for an email and a 4K clip for a video edit.

Why does the text in my SVG look different in the video?

The page can’t download fonts, so text in a font the renderer doesn’t have falls back to a default. Either convert the text to paths in your design tool before you export the SVG, or embed the font in the CSS as a base64 @font-face. The logo in this guide asks for Arial, with Helvetica and any sans-serif font as fallbacks.

Can I make an MP4 with a transparent background?

No. MP4 has no transparency, and a page with a transparent background renders on black, in an MP4 and in a GIF. If the SVG has to sit on top of footage, do it in the same edit, as in the example above. On a web page, use the SVG itself.

Does animation-delay work?

Yes. The logo uses a delay on three of its four animations, so the leaf, the name and the line each start later than the ring. The script adds the delay to the duration when it works out the length of the video.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required