Contents
A headline that types itself out. A quote that lands one word at a time. A title that fades in over the first shot. Animated text is often the difference between a clip and a finished video.
It’s usually made by hand. You pick a preset in After Effects or Premiere, drop it on one layer and adjust it for one line of text.
That works for one video. It gets slow when the words come from a spreadsheet, a CMS or your users, and there are a few hundred of them.
This guide animates text with Python and Shotstack’s video editing API instead. The animation is one setting on a text clip. One script makes a typewriter effect, a word-by-word reveal or a title over footage, and a second one turns a list of quotes into a finished video each.
TL;DR
- Text is a
rich-textclip. Give it ananimationwith apreset, and the text animates in when the clip starts. - There are six presets:
fadeIn,slideIn,typewriter,ascend,shiftandmovingLetters. styleanimates the text by character or by word,directionsets which way it moves, anddurationsets how long the animation takes.- Put the text clip on a track above a video to animate it over footage. A background with
wrapfits the box to the text. - For a list of quotes or headlines, a second script reads a CSV file and renders one video for each row, timed to the length of its text.
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 use the standard library only.
Set the key in your terminal first:
export SHOTSTACK_API_KEY="your_production_key"The six text animations
A Shotstack edit is a JSON timeline of clips. Text goes in a clip with a rich-text asset, and the asset’s animation setting brings it on screen. This video plays the same line with each of the six presets:
| Preset | What the text does | Settings it accepts |
|---|---|---|
fadeIn | Fades in | style, duration |
slideIn | Fades in while it slides into place | style, direction, duration |
typewriter | Types out behind a cursor | style, duration |
ascend | Each word rises or drops into place | direction (up or down), duration |
shift | Fades in while it moves a short distance | style, direction, duration |
movingLetters | Fades in, then the letters ripple for the rest of the clip | direction |
Three settings shape a preset:
styleischaracterorword. It decides whether the text arrives a letter or a word at a time.directionisleft,right,upordown: the way the text travels.durationis the length of the animation in seconds, from 0.1 to 30.
Every preset is an entrance, so it starts when its clip starts. The rich text guide covers the rest of the asset: fonts, gradients, strokes and shadows.
Animate a line of text with Python
Save this script as animate_text.py. The settings at the top hold the text, the animation and the look:
import json
import os
import sys
import time
import urllib.error
import urllib.request
API = "https://api.shotstack.io/edit/v1"
TEXT = "Make every word count."
ANIMATION = {"preset": "typewriter", "style": "character", "duration": 1.6}
LENGTH = 4 # seconds the text is on screen, animation included
FONT = {"family": "Montserrat", "size": 80, "weight": 700, "color": "#ffffff"}
FONT_FILES = [] # links to .ttf or .otf files, for a font that isn't built in
BOX = (1000, 400) # the area the text wraps inside, in pixels
BACKGROUND = "#10151c"
SIZE = (1280, 720)
FPS = 25
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 text_clip(text, animation, length, start=0):
asset = {"type": "rich-text", "text": text, "font": FONT, "animation": animation}
return {
"asset": asset,
"start": start,
"length": length,
"width": BOX[0],
"height": BOX[1],
}
def build_edit(clips):
timeline = {"background": BACKGROUND, "tracks": [{"clips": [c]} for c in clips]}
if FONT_FILES:
timeline["fonts"] = [{"src": link} for link in FONT_FILES]
size = {"width": SIZE[0], "height": SIZE[1]}
return {"timeline": timeline, "output": {"format": "mp4", "size": size, "fps": FPS}}
def render(edit):
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":
return status
if status["status"] == "failed":
sys.exit(f"Render failed: {status.get('error')}")
if __name__ == "__main__":
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
print(f"{ANIMATION['preset']}: {len(TEXT)} characters, {LENGTH} s at {FPS} fps")
status = render(build_edit([text_clip(TEXT, ANIMATION, LENGTH)]))
print(f"MP4: {status['duration']} s")
print(status["url"])Run it:
python animate_text.pyThe script prints what it is about to render, then the link to the MP4:
typewriter: 22 characters, 4 s at 25 fps
Render queued: ee4eb59d-3b24-47b3-aae5-9580b0880113
MP4: 4 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/ee4eb59d-3b24-47b3-aae5-9580b0880113.mp4This is the video from that run:
The file is 1280 x 720 and has 100 frames, which is 4 seconds at 25 fps.
How the script works
- The clip.
text_clipbuilds arich-textasset from the text, the font and the animation. The clip’swidthandheightcome fromBOX. The text wraps inside that box and sits in the middle of it. - The timing.
LENGTHis how long the text is on screen. The animation’sdurationis 1.6, so the line types out first and then holds until the 4 second mark. - The font. Montserrat is one of the built-in fonts, and a
weightof 700 is bold. - The edit.
build_editputs each clip on its own track, sets the background color and asks for an MP4 at the size and frame rate you chose.
To try another preset, change ANIMATION. For example, {"preset": "slideIn", "direction": "left", "duration": 1.5} slides the whole line in from the right.
Get the typewriter effect right
A typewriter effect has three parts: the pace of the typing, whether it types letters or words, and a font that looks the part.
Set the typing pace
Leave duration out, and the API sets the pace for you: about 30 characters a second, never less than 0.3 seconds and never more than 90% of the clip. A line of 31 characters finishes typing just under a second in.
That quick pace suits a short headline: the line is typed, then it holds for the viewer to read.
Text that people read while it appears wants a slower pace. Subtitles are a good yardstick. Netflix’s timed text style guide sets the reading speed for adult programs at “Up to 20 characters per second”.
To type at that speed, set duration to the number of characters divided by 20. For a 31-character line, that is about a second and a half.
Type by letter or by word
With "style": "character" the cursor moves one letter at a time. With "style": "word" each word appears whole, which suits longer sentences.
Use a typewriter font
For the look of a real typewriter, load a font file with FONT_FILES and name it in FONT. Change these settings at the top of the script:
TEXT = "It was a dark and stormy night."
ANIMATION = {"preset": "typewriter"}
FONT = {"family": "Special Elite", "size": 64, "color": "#f4ecd8"}
FONT_FILES = ["https://shotstack-assets.s3.amazonaws.com/fonts/SpecialElite-Regular.ttf"]The line is the opening of Edward Bulwer-Lytton’s 1830 novel Paul Clifford. Here it is at the default pace:
The font file has to be a TTF or OTF file at a public link. family is the name stored inside the font, the one you see when you install it. The file name without its extension, SpecialElite-Regular, works as well.
Reveal a line word by word
A quote or a tagline often reads best when the words arrive one at a time. ascend does that with a small rise on each word. Change these three settings:
TEXT = "Small steps, taken daily, cover the longest roads."
ANIMATION = {"preset": "ascend", "direction": "up", "duration": 2.4}
LENGTH = 5The eight words take 2.4 seconds to arrive, then the line holds until the 5 second mark. Set direction to down and the words drop in from above.
ascend always works by word. For a different feel, use fadeIn, slideIn or shift with "style": "word". The words still arrive one at a time, but they fade or slide into place.
Animate a title over footage
So far the text has had a plain background. To animate it over a video, put the text clip on a track above the footage.
Save this as text_over_video.py, next to animate_text.py:
"""Put an animated title over footage: a text clip on a track above a video."""
import os
import sys
import animate_text
FOOTAGE = "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/footage/skier.mp4"
TITLE = "Fresh snow, first lift, no queue."
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
animate_text.FONT = {
"family": "Montserrat",
"size": 44,
"weight": 700,
"color": "#ffffff",
}
animate_text.BOX = (1000, 120)
animation = {"preset": "shift", "direction": "up", "duration": 1}
title = animate_text.text_clip(TITLE, animation, 4, start=0.6)
title["asset"]["padding"] = 20
title["asset"]["background"] = {"color": "#10151c", "borderRadius": 14, "wrap": True}
title["asset"]["align"] = {"horizontal": "left", "vertical": "middle"}
title["position"] = "bottomLeft"
title["offset"] = {"x": 0.04, "y": 0.06}
video = {"type": "video", "src": FOOTAGE, "volume": 0}
edit = animate_text.build_edit([title, {"asset": video, "start": 0, "length": 5}])
status = animate_text.render(edit)
print(f"MP4: {status['duration']} s")
print(status["url"])Render queued: 5a1abc26-3194-40e1-a27a-cbd85d9c6802
MP4: 5 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/5a1abc26-3194-40e1-a27a-cbd85d9c6802.mp4Four things differ from the first script:
- Two tracks.
build_editgets the title first and the video second. The first track is the top layer. - A late start. The title starts at 0.6 seconds, so the shot is on screen before the text arrives.
- A box that fits. The
backgroundgives the title a dark box so it stays readable on snow. With"wrap": Truethe box takes the width of the text plus thepadding, not the width of the clip. - A corner.
positionmoves the clip to the bottom left, andoffsetbrings it in from the edges.
The wrapped box matters most when you don’t write the text yourself. A title that comes from a form or a database can be two words or ten, and the box fits either.
Make a video for every quote in a list
One animated line is quick to make in any editor. A quote for every day of the month is where a script earns its place.
The list is a CSV file. Each row holds a quote, its author, a preset and a background color. Save it as quotes.csv:
quote,author,animation,background
Our life is frittered away by detail.,Henry David Thoreau,ascend,#10151c
Brevity is the soul of wit.,William Shakespeare,typewriter,#1d3557
The only way to have a friend is to be one.,Ralph Waldo Emerson,fadeIn,#3d2c4dSave this script as animate_quotes.py, next to animate_text.py:
"""Make one animated quote video for every row of quotes.csv."""
import csv
import os
import sys
import time
import urllib.request
from pathlib import Path
import animate_text
OUT = Path("quotes")
WORD_PACE = 0.32 # seconds each word takes to appear
READING_TIME = 0.3 # seconds a word, to read the finished quote
MARGIN = 1.6 # extra seconds on screen after that
animate_text.SIZE = (1080, 1920)
animate_text.BOX = (900, 1000)
animate_text.FONT = {
"family": "Montserrat",
"size": 100,
"weight": 700,
"color": "#ffffff",
}
def whole_frames(seconds):
return round(seconds * animate_text.FPS) / animate_text.FPS
def quote_edit(row):
words = len(row["quote"].split())
reveal = whole_frames(words * WORD_PACE)
hold = whole_frames(words * READING_TIME + MARGIN)
animation = {"preset": row["animation"], "style": "word", "duration": reveal}
quote = animate_text.text_clip(row["quote"], animation, reveal + hold)
fade = {"preset": "fadeIn", "duration": 0.6}
author = animate_text.text_clip(row["author"], fade, hold, start=reveal)
author["asset"]["font"] = {"family": "Montserrat", "size": 46, "color": "#8fd3ff"}
author["height"] = 120
author["offset"] = {"x": 0, "y": -0.2}
animate_text.BACKGROUND = row["background"]
return animate_text.build_edit([quote, author])
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
renders = {}
with open("quotes.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
response = animate_text.call(f"{animate_text.API}/render", quote_edit(row))
name = row["author"].lower().replace(" ", "-") + ".mp4"
renders[response["response"]["id"]] = (name, row["animation"])
print(f"Queued {len(renders)} renders")
OUT.mkdir(exist_ok=True)
while renders:
time.sleep(5)
for render_id in list(renders):
status = animate_text.call(f"{animate_text.API}/render/{render_id}")["response"]
if status["status"] == "failed":
print(f"{renders.pop(render_id)[0]}: failed, {status.get('error')}")
elif status["status"] == "done":
name, animation = renders.pop(render_id)
urllib.request.urlretrieve(status["url"], OUT / name)
print(f"{name}: {animation}, {status['duration']} s")Run it, and it queues one render for each row and downloads the results to a quotes folder:
Queued 3 renders
henry-david-thoreau.mp4: ascend, 5.92 s
william-shakespeare.mp4: typewriter, 5.32 s
ralph-waldo-emerson.mp4: fadeIn, 8.44 sThe quotes differ in length, so one fixed timing doesn’t suit them all. The script times each video from its word count:
- The reveal. Each word gets 0.32 seconds, so a longer quote takes longer to arrive.
- The hold. The finished quote stays up for 0.3 seconds a word, plus 1.6 seconds.
- The author. A second text clip starts at the moment the reveal ends and fades in below the quote.
The 0.3 seconds comes from the BBC’s subtitle guidelines: “you should aim to leave a subtitle on screen for a minimum period of around 0.3 seconds per word”. The guidelines call that a minimum, which is why the script adds time on top of it.
Thoreau’s seven words make a 5.92 second video. Emerson’s eleven make one of 8.44 seconds.
The videos are 1080 x 1920, the shape that Reels, Shorts and TikTok use. Our guide to vertical video safe zones shows where each app covers the frame with its own buttons.
When the list lives in a spreadsheet tool or a CMS, you can keep the design in one place. Put {{quote}} and {{author}} where the text goes, and send the values with each render. The merge fields guide shows how.
Go beyond the presets
The six presets cover the text animations most videos need. For anything else, such as an effect you’ve already built in CSS, write the animation as a small web page and render it with an html5 clip. Our guide to converting an HTML animation to MP4 shows how that works.
A number that counts up is made the same way, and it has a guide of its own: how to make a count-up number animation video.
Can FFmpeg animate text?
It can, and for a fade it’s short. FFmpeg’s drawtext filter has an alpha option that takes an expression. The documentation says: “Draw the text applying alpha blending. The value can be a number between 0.0 and 1.0.”
So alpha='min(t/1.6,1)' fades a line in over 1.6 seconds.
A typewriter effect is more work, because drawtext draws a whole string at once. One way to do it is a drawtext for each step of the typing, each switched on at its own time with enable.
I built the 22-character line from this guide that way with FFmpeg 8.1. It took 22 chained filters and a filter string 3,144 characters long, and the result has no cursor.
Animate the text in every video with Shotstack
A typed headline, a quote that arrives word by word and a title over footage are now each one setting on a text clip. The same setting works for a list: every row of the CSV came back as a finished video, timed to its own length.
To change the look of all of them, edit the font, the colors and the preset at the top of the script.
Sign up for a free Shotstack API key and animate your first line of text.
Frequently asked questions (FAQs)
Can the text animate out as well?
The presets bring text in. To take it off screen, add a transition to the clip, for example "transition": {"out": "fade"}. A line with a typewriter animation and that transition types out, holds, and fades away at the end of the clip.
Can I make an animated text GIF?
Yes. Set the output format to gif and add "repeat": true so it loops. Keep the frame rate at 25 fps so the GIF plays at the right speed. Our guide to converting an animated SVG to GIF explains why that frame rate matters for GIFs.
Can the words follow a voiceover?
The presets run at an even pace. For words that appear as they are spoken, use a rich-caption clip, which takes its timing from the audio.
The guide to burning subtitles into a video transcribes the speech of a clip and highlights each word as it’s said. The guide to making a lyric video does it for a song, from a lyrics file.
Which fonts are built in?
Roboto, Montserrat, Open Sans, Work Sans, Uni Neue, Arapey, Clear Sans, Didact Gothic, MovLette, Permanent Marker and Sue Ellen Francisco. Any other font works as a file, as in the typewriter example above.