跪拜 Guibai
← Back to the summary

Who's Actually Playing Your SVG Animation? Turning Mermaid Step Sequences Into GIFs

Who Is Actually Playing the Animation in SVG?

When making courseware, I needed a diagram that explains the "request sequence": click login → get code → exchange openid → render logged-in state. Mermaid's step animation plays along edges in order; I marked the three edges with step 1/2/3 and used the command-line tool mmdc to export an SVG.

Once the file was on disk, I asserted that "a static export won't move." But when I opened it in Chrome, the dot ran along the edge. That statement mistook "exported to a file" for "became static": SVG can carry its own animation declarations, and the browser executes them when opened. Only when it is converted to a raster format like PNG does it truly freeze a frame. When I later needed to put this diagram into a PPT, I ran into the second problem: how to turn the browser's timeline into a bitmap that plays frame by frame without the browser.

This post records the second problem. First, clarify who is playing the animation; then read the timeline from the SVG source; finally export frame by frame and verify.

A Comparison Table

Mechanism Where the declaration is written Who executes When introduced via <img> Corresponding element in this example
SMIL <animateMotion> / <animateTransform> elements Browser SVG engine Still runs Dot movement, current edge highlight
CSS <style> + @keyframes / @media inside SVG Browser CSS engine Still runs Dashed line flow, hiding when reduced motion is set
JavaScript <script> or external mermaid.js JS engine Disabled Not used in this example

The first two are self-contained: the animation declarations are inside the .svg file and do not need the Mermaid runtime. So Chrome opens it and it moves, and using <img src="x.svg"> in a webpage generally also moves — the image context only disables scripts, not SMIL or CSS.

1. The Animation Is Written in the SVG, Not in mmdc

Positioning First, identify the execution subject. mmdc renders the Mermaid source into an SVG text file and exits; the browser parses the animation declarations only when it opens that SVG. Replacing the SVG with a GIF isn't "making the animation move"; it's converting the browser's already-playing timeline into a sequence of bitmap frames.

Method Open the exported SVG and you'll find three kinds of declarations:

<!-- Dot moving along edge: SMIL -->
<circle class='edge-step-dot' r='4' transform='translate(164,118.6) scale(0)'>
  <animateMotion begin='0s;step_..._e1_step.end+2s' dur='1s'
                  id='step_..._e1_step' path='M164,118.6L200,118.6'/>
  <animateTransform attributeName='transform' type='scale' values='1;1' dur='1s'/>
</circle>
/* Current edge highlight, and hiding when reduced motion is set */
.edge-step-highlight { stroke-width: 4; stroke-opacity: .6; }
@media (prefers-reduced-motion: reduce) {
  #my-svg .edge-step-dot, #my-svg .edge-step-highlight { display: none; }
}

The number badge is a purely static element with no animation attributes:

<g class='edge-step-badge' data-step='1'><circle r='9'/><text>1</text></g>

Boundary Because the badge doesn't participate in animation, it's the only order marker that is stable in every environment. The @keyframes dash dashed line flow is a CSS animation unrelated to the step animation; don't confuse them. Also, the Chinese characters inside nodes are in <foreignObject> — HTML text, not native SVG <text>; that becomes a key difference in section 2.

Verification method grep -oE "animateMotion|@keyframes|<script" x.svg. If SMIL or CSS is present and there is no <script>, the SVG is self-contained and will animate without mermaid.js.

2. Why Static Converters Can't Do It

Positioning With a self-contained SVG, the most obvious approach is to have rsvg-convert, cairosvg, or ImageMagick convert directly. They do not implement the SVG animation timeline; they only draw a single frame according to the current DOM state.

Method Use the same file for a direct conversion (replace the path with your own SVG):

rsvg-convert -w 1472 your.svg -o /tmp/direct.png

Figure 2: The same SVG, direct conversion vs. browser frame-by-frame

Boundary In practice it's worse than "missing animation": rsvg-convert also does not render HTML text inside <foreignObject>, so all Chinese characters in nodes are empty; the number badge remains because it uses native <circle><text>. The judgment is not "looks different" but that the converter doesn't interpret <animateMotion> at all, leaving the animation element stuck at its initial scale(0) state. Figure 2 juxtaposes that.

So to capture animation, the browser must participate and take frame-by-frame screenshots.

Verification method Put the direct output and a browser frame side by side (Figure 2). If node text is empty and edges aren't bold, the converter didn't run the timeline; adjusting its parameters is pointless.

3. Reading the Timeline: The Period Is Not Something You Look Up

Positioning The GIF duration depends on the loop period. This value isn't in documentation or command-line arguments; it's written in the SVG's begin and dur.

Method Extract one edge from the source:

<animateMotion begin='0s;step_..._e1_step.end+2s' dur='1s' id='step_..._e1_step' .../>
What is read Value Conclusion
dur 1s Each edge plays for 1 second
First begin 0s / 1s / 2s Three steps start sequentially
Repeat base id.end + 2s Wait 2 seconds after its own end
Single edge period 1 + 2 = 3s Replays every 3 seconds
Overall 0, 1, 2, 3, 4, 5 … Changes step every second, no pause, 3-second cycle

Taking 0–3 seconds as the loop, the third second returns to step 1, making the beginning and end seamless. Figure 1 shows the same diagram at 0.5 / 1.5 / 2.5 seconds.

Figure 1: Three moments of the step animation

Boundary Identical step numbers mean simultaneous playback, not sequential: in a parallel branch, two edges labeled step: 2 will light up together. If the animation is written in CSS, you would read animation-duration and animation-iteration-count instead; confirm the execution subject before reading parameters.

Verification method Use a different diagram, run grep -o "begin='[^']*'" x.svg to see if the repeat base is id.end+Ns; if so, the period is dur + N.

4. Two Judgments for Frame-by-Frame Sampling

Positioning With the period in hand, you still need to decide how to turn the timeline into a deterministic frame sequence.

Method The core is only four lines:

await page.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'no-preference' }]);
await page.evaluate(() => document.querySelector('svg').pauseAnimations());
await page.evaluate(t => document.querySelector('svg').setCurrentTime(t), i / FPS);
await el.screenshot({ path: `f_${String(i).padStart(3, '0')}.png` });

Then let ffmpeg compose:

ffmpeg -framerate 12 -i f_%03d.png \
  -filter_complex '[0:v]split[a][b];[a]palettegen=stats_mode=full[p];[b][p]paletteuse=dither=sierra2_4a' \
  -loop 0 -gifflags +transdiff out.gif

Boundary Three easily missed points:

  1. prefers-reduced-motion must be explicitly set to no-preference. The @media rule in the SVG hides the dot and highlight with display:none when reduce is on; it doesn't error or warn, and the output is a static image.
  2. Use setCurrentTime(t) instead of sleep. A screenshot takes tens of milliseconds; sleeping to sample frames makes the interval drift and the loop seam stutter; seeking is deterministic so re-capturing the same moment gives the same frame.
  3. In a standalone SVG document, document.documentElement is the root <svg>; pinning width/height to the viewBox size removes extra whitespace; width='100%' in a standalone document stretches to the viewport.

Verification method Capture frames at 0.3 / 1.3 / 2.3 seconds and compare hashes, then return to 0.3 seconds and compare again. If the first three differ from each other and the first and last match, the seek works.

5. Verification: Don't Just Check Exit Code 0

Positioning Each of the above steps might "succeed but not be correct", so three layers of verification are needed.

Method First, inspect the product structure:

ffprobe -v error -select_streams v:0 \
  -show_entries stream=nb_frames,width,height -show_entries format=duration \
  -of default=nw=1 out.gif

The three products here all have 36 frames / 3.000s, dimensions 1928×170, 1928×170, 1472×458, 29–46 KB.

Second, check frame hashes: among the 36 frames, 30, 27, and 34 frames respectively are distinct. If there are only one or two frame types, the animation never played; the reduced-motion issue from section 4 is the most common culprit.

Third, extract frames from the beginning, middle, and end and look at them.

Boundary This layer also corrected an assumption of mine: the dot has r=4, so at 2x screenshot it's only 8px and often overlaps the number badge, making it nearly invisible in a single frame. The reliably discernible element is the current edge's bold highlight. So "it looks like it moved" isn't a criterion; frame hash differences are.

Verification method Stop at any of the three layers if it fails: if the frame count is wrong, check the sampling loop; if hashes show only a few types, check reduced-motion; if the eye can't see a change, enlarge the image and look at the bold highlight on the current edge.

6. When to Keep SVG and When to Output GIF

Positioning The deciding factor isn't resolution, but whether the target environment has an SVG runtime.

Method Choose based on the environment:

Environment Animation Number badge Which to use
Chrome opens .svg directly plays present keep SVG
Webpage <img src="x.svg"> / inline SVG plays present keep SVG
mmdc -o x.png frozen present handouts screenshot
PPT / Word / PDF / print frozen present output GIF
WeChat, official accounts, etc. that only accept bitmaps frozen present output GIF
GIF frame-by-frame bitmap plays present any environment
System "reduce motion" enabled dot and highlight hidden present rely on badge

Boundary The system preference only affects the CSS rule in the SVG; a GIF is a bitmap and is unaffected. So the conclusion that "the badge is present in every environment" relies precisely on it not being part of the animation. The value of a GIF isn't a "clearer SVG" but a format that doesn't depend on an SVG runtime.

Verification method Insert the file into the target environment and look. In PPT, Word, PDF, and print preview, SVG animations are always frozen; don't expect them to move.

How To Do It

  1. First grep to confirm the animation mechanism is SMIL / CSS or JS, and determine whether the SVG is self-contained.
  2. Derive the loop period from begin / dur, don't guess the GIF length.
  3. Use the browser to seek frame by frame, explicitly turn off reduced-motion; don't use sleep or static converters.
  4. Use ffprobe for frame count and duration → frame hashes for differences → extract frames and look.
  5. Keep SVG for webpages; output GIF for PPT / Word / official accounts; generate a separate PNG for handouts.
  6. Check version details according to the notes at the end, don't just report mmdc --version.

Appendix A: Classroom Use

Handouts need the sequence; classroom presentations need the process, and the requirements are opposite. The following Mermaid source enables stepNumbers. Save it as login.mmd and export per target environment:

The following uses the step-animation syntax of mermaid 12.3.0. The built-in Mermaid version on Juejin is older; labeling it mermaid will fail to render. It's shown as plain code; to see the effect, paste into mermaid.live or use local mmdc.

---
config:
  flowchart:
    stepNumbers: true
---
flowchart LR
  U["用户点击登录"] e1@--> L["wx.login 拿 code"]
  L e2@--> S["云函数换 openid"]
  S e3@--> V["setData 渲染登录态"]

  e1@{ step: 1 }
  e2@{ step: 2 }
  e3@{ step: 3 }
mmdc -i login.mmd -o login.svg   # 课堂演示,浏览器里播动画
mmdc -i login.mmd -o login.png   # 讲义 / PPT,定格但徽章可读
NODE_PATH="$(pnpm root -g)" node make-gif.js   # 出可在任何环境播放的 GIF

登录链路的循环 GIF

e1@--> gives the edge an ID, e1@{ step: 1 } declares the order on a separate line; identical step numbers play in parallel, which suits explaining concurrent requests (e.g., a cloud function querying both user table and order table). In static export the dot doesn't play, but the number badge opened by stepNumbers: true is drawn into the image and remains readable in print, projection, and PDF, so handouts prefer the badge.

Appendix B: Script and Assets

The accompanying script does exactly the four lines from section 4 as a loop: it detects the local chrome-headless-shell → screenshots at each setCurrentTime(t) → ffmpeg composes the GIF. The input is any SVG with SMIL animation, and the output is a same-named .gif; replace src/ with your own file to reuse, no script changes needed.

NODE_PATH="$(pnpm root -g)" node make-gif.js

NODE_PATH is needed because puppeteer is installed in the pnpm global directory and plain require can't find it. The script auto-detects the executable in ~/.cache/puppeteer/chrome-headless-shell/ and also recognizes PUPPETEER_EXECUTABLE_PATH and PUPPETEER_CACHE_DIR. Intermediate frames are written to the system temp directory so the working directory isn't polluted. The two images in this post were generated by the same frame-by-frame capture plus an HTML composition script; each caption notes the source time. The three GIFs are direct outputs of the script.

Notes: Environment and Versions

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

Swot

Actually doesn't touch .mmd; that term was removed after the modification.