Contents
“12,480 orders shipped” is a line in a report. Watch the same number climb from zero and land on 12,480, and it becomes the point of the video.
Count-up animations show up in launch posts, year-end recaps, investor updates and on top of product footage. On a web page, a counter is a few lines of JavaScript. As a video file, it usually means opening a motion design tool and keying the number by hand, again for every number and every time the numbers change.
This guide makes the animation with Python and Shotstack’s video editing API instead. You give a script a number and a label, and it returns an MP4 or a GIF. A second script counts the number up over footage, and a third makes a clip for every row of a CSV file.
TL;DR
- Put a small web page in an
html5clip and count the number with a GSAP tween. The renderer captures every frame at its exact time. - The tween ends on the value itself, so the last frames show 12,480 and not 12,479.
- Settings at the top of the script handle
$,%, decimals, separators, the speed curve and the size. - Set the format to
giffor a GIF, and give the page a see-through background to count over footage. - A CSV of statistics becomes one clip for each row, plus one reel that plays them all.
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.
Set the key in your terminal before you run anything:
export SHOTSTACK_API_KEY="your_production_key"Why the count is a tween, not a timer
In Shotstack, a video is described as JSON: a timeline of clips. An html5 clip renders a small web page as video, and you pass the page as three strings: html, css and js. The number, the label and the script that counts all live in that page.
The renderer doesn’t play the page and record it. For each frame, it moves the page’s animations to that frame’s time and captures the result. Our guide to converting an HTML animation to MP4 covers how that works.
So the count has to be an animation, not a timer. A timer follows the clock, and a render has no clock to follow. A GSAP tween can answer for any moment: “what is the value at 1.2 seconds?”
The HTML5 docs name this method for values that change over time: drive the value with a GSAP tween and its onUpdate function.
GSAP is already loaded on the page, and there’s a fair chance you know it. The 2024 Web Almanac reports that “libraries like GSAP (9%), OWL Carousel (8%), Slick (8%), LazySizes (8%), and FancyBox (7%) continue to be widely used”. The tween below is the one you’d write for a website.
Make a count-up video with Python
Save this script as count_up.py:
import html
import json
import os
import sys
import time
import urllib.error
import urllib.request
API = "https://api.shotstack.io/edit/v1"
VALUE = 12480 # the number the count lands on
LABEL = "orders shipped"
PREFIX = "" # goes before the number, for example "$"
SUFFIX = "" # goes after the number, for example "%" or "+"
DECIMALS = 0
FROM = 0 # the number the count starts at
COUNT = 2.5 # seconds the count takes
HOLD = 1.5 # seconds the final number stays on screen
EASE = "power2.out" # a GSAP ease: fast at first, slower near the end
LOCALE = "en-US" # sets the separators: 12,480 in en-US, 12.480 in de-DE
FORMAT = "mp4" # "mp4" or "gif"
WIDTH, HEIGHT = 1280, 720
SIZE = 200 # font size of the number in pixels
FPS = 25
BACKGROUND = "#0b1f3a"
COLOR = "#ffffff"
FONT = "Arial, Helvetica, sans-serif"
PAGE_JS = """
const number = document.getElementById("number");
const count = { value: s.from };
const digits = { minimumFractionDigits: s.decimals, maximumFractionDigits: s.decimals };
const show = () => {
number.textContent = s.prefix + count.value.toLocaleString(s.locale, digits) + s.suffix;
};
show();
gsap.timeline().to(count, { value: s.value, duration: s.count, ease: s.ease, onUpdate: show });
"""
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 stat_clip(value, label, prefix="", suffix="", decimals=0, start=0):
"""An html5 clip that counts up to value, then holds the final number."""
settings = {
"from": FROM,
"value": value,
"count": COUNT,
"ease": EASE,
"locale": LOCALE,
"prefix": prefix,
"suffix": suffix,
"decimals": decimals,
}
page = f'<div class="stat"><div id="number"></div><div>{html.escape(label)}</div></div>'
css = (
f"html, body {{ margin: 0; width: {WIDTH}px; height: {HEIGHT}px;"
f" overflow: hidden; background: {BACKGROUND}; }}"
f" .stat {{ width: {WIDTH}px; height: {HEIGHT}px; display: flex;"
" flex-direction: column; align-items: center; justify-content: center;"
f" font-family: {FONT}; font-size: {SIZE // 4}px; color: {COLOR}; }}"
f" #number {{ font-size: {SIZE}px; font-weight: 700;"
" font-variant-numeric: tabular-nums; }"
)
return {
"asset": {
"type": "html5",
"html": page,
"css": css,
"js": f"const s = {json.dumps(settings)};{PAGE_JS}",
},
"start": start,
"length": COUNT + HOLD,
"width": WIDTH,
"height": HEIGHT,
}
def build_edit(clips):
output = {"format": FORMAT, "size": {"width": WIDTH, "height": HEIGHT}, "fps": FPS}
if FORMAT == "gif":
output["repeat"] = True
return {"timeline": {"tracks": [{"clips": clips}]}, "output": output}
def wait(render_id):
"""Poll a render until it is done and return its status."""
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.")
edit = build_edit([stat_clip(VALUE, LABEL, PREFIX, SUFFIX, DECIMALS)])
print(f"{PREFIX}{VALUE:,}{SUFFIX} {LABEL}: {WIDTH} x {HEIGHT}, {COUNT + HOLD} s")
render_id = call(f"{API}/render", edit)["response"]["id"]
print("Render queued:", render_id)
status = wait(render_id)
print(f"{FORMAT.upper()}: {status['duration']} s")
print(status["url"])Run it:
python count_up.pyThe script prints what it’s making, then the link to the MP4:
12,480 orders shipped: 1280 x 720, 4.0 s
Render queued: 6a1da5bf-f8ea-4f98-a7ce-075ad4e4ab13
MP4: 4 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/k8w3n5r2hd/6a1da5bf-f8ea-4f98-a7ce-075ad4e4ab13.mp4Here is the MP4 from that run:
The file is 1280 x 720 and 4 seconds long: 2.5 seconds of counting and 1.5 seconds on the final number.
How the script works
- The page. Two
divelements, one for the number and one for the label, centered with flexbox. The CSS pins the page to the size of the clip in pixels. - The count. GSAP moves
count.valuefromFROMtoVALUEoverCOUNTseconds. On every frame,onUpdatecallsshow, which writes the number into the page. - The format.
toLocaleStringadds the thousands separators and fixes the number of decimals. It also rounds, so a count to 12,480 never shows a fraction on the way up. - Steady digits.
font-variant-numeric: tabular-numsasks the font for digits of equal width, so the number doesn’t shake as the digits change. - The length. The clip lasts
COUNT + HOLDseconds. The hold gives people time to read the final number.
The number lands on the exact value
A counter that adds a step on every tick can stop one short, or overshoot and snap back. A tween can’t. Its last value is VALUE itself, whatever the speed curve.
In the MP4 above, the frame at 2.4 seconds reads 12,479. The frame at 2.48 seconds reads 12,480, and so does every frame after it.
Set the number, the label and the format
Every setting is a line at the top of the script. These are the ones that change what the number looks like:
| For this | Change these settings | The last frame shows |
|---|---|---|
| A percentage | VALUE = 98.6, SUFFIX = "%", DECIMALS = 1 | 98.6% |
| Money | VALUE = 1250000, PREFIX = "$" | $1,250,000 |
| ”More than” | VALUE = 47, SUFFIX = "+" | 47+ |
| German separators | VALUE = 1250000, LOCALE = "de-DE" | 1.250.000 |
| A count down | FROM = 100, VALUE = 0 | 0 |
SIZE is the font size of the number in pixels, and the label is a quarter of it. At 200 pixels, $1,250,000 fills most of a 1280 pixel frame. Lower SIZE for a longer number or a narrower frame.
For a vertical video, change the frame and the size together:
WIDTH, HEIGHT = 1080, 1920
SIZE = 160FONT takes a font that the renderer already has, such as Arial or Georgia. The FAQs cover brand fonts.
Choose how the count slows down
EASE sets the speed curve of the count. It takes the name of a GSAP ease. This render runs the same count with three of them:
One second into a 2.5 second count to 12,480, the three clips read:
EASE | After 1 second | How it feels |
|---|---|---|
"none" | 4,992 | The same speed all the way, like a meter |
"power2.out" | 9,784 | Fast at first, then it settles |
"power4.out" | 11,510 | A rush, then a long slow finish |
An ease that ends slowly suits a statistic. The big digits fly past, and the eye gets time to catch the last ones as they settle. Keep "none" for things that should tick evenly, such as a timer.
Make a count-up GIF
Change three settings:
FORMAT = "gif"
WIDTH, HEIGHT = 480, 270
SIZE = 76The script adds "repeat": true to the output, so the GIF loops and the count starts again:
Keep FPS at 25. A GIF can’t store every frame rate exactly, and 25 is one it can. Our guide to converting an animated SVG to a GIF shows what happens at other rates.
A GIF is the heavier file. This 480 x 270 GIF is 1 MB, and the 1280 x 720 MP4 of the same count is 212 KB. Use the MP4 wherever video plays, and keep the GIF for places that only take images.
Count up over footage
A statistic often belongs on top of a video: the number of cities over a skyline, a distance over a race. The page of an html5 clip is see-through unless you give it a background, so the number only needs a video on the track below it.
Save this as count_over_video.py, next to count_up.py:
"""Count a number up over footage: an html5 clip on a track above a video."""
import os
import sys
import count_up
FOOTAGE = "https://shotstack-assets.s3.amazonaws.com/footage/drone-city-flyover.mp4"
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
count_up.WIDTH, count_up.HEIGHT = 480, 270 # the size of the panel on the video
count_up.SIZE = 130
count_up.BACKGROUND = "rgba(11, 31, 58, 0.8)" # "transparent" shows no panel
panel = count_up.stat_clip(47, "cities", suffix="+")
panel["position"] = "bottomLeft"
panel["offset"] = {"x": 0.05, "y": 0.08}
video = {"type": "video", "src": FOOTAGE, "volume": 0}
footage = {"asset": video, "start": 0, "length": panel["length"]}
edit = {
"timeline": {"tracks": [{"clips": [panel]}, {"clips": [footage]}]},
"output": {"format": "mp4", "size": {"width": 1280, "height": 720}, "fps": 25},
}
render_id = count_up.call(f"{count_up.API}/render", edit)["response"]["id"]
print("Render queued:", render_id)
status = count_up.wait(render_id)
print(f"MP4: {status['duration']} s")
print(status["url"])It prints the link to the finished video:
Render queued: 98765f95-4cfe-415b-ae2f-46ce10fb50d4
MP4: 4 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/k8w3n5r2hd/98765f95-4cfe-415b-ae2f-46ce10fb50d4.mp4The script makes the page as small as the panel, 480 x 270 pixels, then places it with position and offset. Sizing the clip to its content keeps the layout easy to reason about. Both settings are explained in the positioning guide.
The background is a color with 80% opacity, which gives the dark panel. Set BACKGROUND to "transparent" and the number sits straight on the footage.
Make a clip for every row of a CSV
Numbers rarely come one at a time. A monthly report has a handful, and a year-end recap has a set for every customer. People share those. In its fourth quarter 2025 results, Spotify said its Wrapped recap “had more than 300 million engaged users and more than 630 million shares on social media”.
So keep the numbers in a file and let a script make the clips. Save this as stats.csv:
value,label,prefix,suffix,decimals
12480,orders shipped,,,0
98.6,delivered on time,,%,1
1250000,raised for local schools,$,,0
47,cities,,+,0Save this script as count_from_csv.py, next to count_up.py:
"""Make a count-up clip for every row of stats.csv, and one reel that plays them all."""
import csv
import os
import re
import sys
import time
import urllib.request
from pathlib import Path
import count_up
OUT = Path("stats")
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
clips = {}
with open("stats.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
name = re.sub(r"[^a-z0-9]+", "-", row["label"].lower()).strip("-")
clips[name] = count_up.stat_clip(
float(row["value"]),
row["label"],
row["prefix"],
row["suffix"],
int(row["decimals"] or 0),
)
edits = {name: count_up.build_edit([clip]) for name, clip in clips.items()}
reel = [dict(clip, start=i * clip["length"]) for i, clip in enumerate(clips.values())]
edits["reel"] = count_up.build_edit(reel)
renders = {}
for name, edit in edits.items():
response = count_up.call(f"{count_up.API}/render", edit)
renders[response["response"]["id"]] = f"{name}.mp4"
print(f"Queued {len(renders)} renders")
OUT.mkdir(exist_ok=True)
while renders:
time.sleep(5)
for render_id in list(renders):
status = count_up.call(f"{count_up.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, and it queues every render at once and saves each file as it finishes:
Queued 5 renders
orders-shipped.mp4: 4 s, 212 KB
raised-for-local-schools.mp4: 4 s, 339 KB
cities.mp4: 4 s, 80 KB
reel.mp4: 16 s, 815 KB
delivered-on-time.mp4: 4 s, 190 KBEach row becomes its own MP4 in the stats folder, named after its label. Those are the files for separate posts or slides.
The last render is the reel. The script takes the same four clips, gives each one a start time straight after the one before, and sends them as a single edit. Four rows of 4 seconds make one 16 second video:
When the numbers change, change the CSV and run the script again. To skip even that step, export the CSV from your database and run the script on a schedule. Our guide to automating video creation on a schedule sets that up with cron.
Can FFmpeg make a count-up animation?
Yes, for a plain whole number. FFmpeg’s drawtext filter can print the result of an expression, and the expression can use the time t. This command counts to 12,480 in 2.5 seconds, with a bold Arial font file in the same folder:
ffmpeg -f lavfi -i "color=c=0x0b1f3a:s=1280x720:r=25:d=4" -vf "drawtext=fontfile=arialbd.ttf:text='%{eif\:min(12480\,12480*t/2.5)\:d}':fontsize=200:fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2" count.mp4It works, and the result shows where the approach runs out. The number reads 12480, with no comma. The FFmpeg documentation describes the eif function in one line: “Evaluate the expression’s value and output as formatted integer.” Whole numbers are all it prints.
Separators, decimals, a slow finish and a label each mean more expression math and more escaping. On a page, they’re one line of CSS or JavaScript each. If you’re new to the tool, start with our guide on how to use FFmpeg.
Put your numbers in motion with Shotstack
A number and a label go in, and a count-up video or GIF comes out, landing on the exact value. The same clip sits over footage. A CSV gives you a clip for every statistic and a reel of them all.
Nothing here needs a motion design tool, and next month’s numbers are a new CSV away.
Sign up for a free Shotstack API key and count up your first number.
Frequently asked questions (FAQs)
Can I use my brand font?
Yes, if you put the font inside the CSS. The page can’t download files while it renders, so a link to a font on the web won’t load. The HTML5 docs show the way to do it: add an @font-face rule with the font file encoded as base64 in a data: URL, then name that family in FONT.
The css string holds up to 500,000 characters, so a compact .woff2 file works best.
Can the number show as $1.3M instead of $1,250,000?
Yes. In PAGE_JS, replace the digits line with this one:
const digits = { notation: "compact", maximumFractionDigits: 1 };The count then runs in short form the whole way. In my render of the $1,250,000 row it read $980K after one second and ended on $1.3M.
Can I make a timer or a stopwatch?
Yes. Set EASE = "none" so the seconds tick evenly, and set VALUE and COUNT to the same number of seconds. Then replace the line inside show with these two:
const t = Math.floor(count.value);
number.textContent = Math.floor(t / 60) + ":" + String(t % 60).padStart(2, "0");With VALUE = 10 and COUNT = 10, the clip starts at 0:00 and reaches 0:10 ten seconds later.
Can I show several numbers in one frame?
Yes. Make a clip for each number with stat_clip, put each clip on its own track, and move them apart with offset. Set WIDTH, HEIGHT and SIZE to the size of one number first. Three clips of 400 x 300 pixels, with offset.x at -0.33, 0 and 0.33, sit side by side in a 1280 x 720 frame.
Can I send the number as a merge field?
Yes. The html string of an html5 clip takes merge fields. Put the field in the page, for example <div id="number" data-value="{{VALUE}}">, and read it in the script with Number(number.dataset.value).
The values then go in the merge list of the request, so the page itself never changes. A request with VALUE set to 8315 and a label field set to “new members” counted to 8,315 new members.