Vijendra Rana

Search

Search articles, series and snippets

animate-mermaid - Mermaid diagrams that draw themselves

By · · 15 min read · Developer Tools, Diagrams

#mermaid #javascript #typescript #react #svelte #svg

A small library that animates Mermaid diagrams in graph order and exports them as animated SVG, GIF or PNG, from any framework.

On this page

Mermaid is the easiest way to put a diagram in a README, a doc site or a blog post. You write a few lines of text and get a clean SVG. What you do not get is a story. The whole diagram lands on the page at once, and the reader has to work out where it starts, which way the arrows go and what happens after what.

When I explain an architecture out loud, I draw it one box at a time. The client first, then the arrow to the API, then the database. I wanted my diagrams to do the same, so I built animate-mermaid.

A request through a typical web stack

That diagram is plain Mermaid. The library reads the graph, works out the order, and adds CSS keyframes so each node pops in after the edge that leads to it.

What it does

  • Follows the graph. Roots appear first, each edge draws toward its target, then the target pops in. Subgraphs fade in just before their contents.
  • Light and smooth. Pure CSS keyframes, so it runs on the browser’s compositor. No animation loop, no GSAP. The core is about 6 KB gzipped, with Mermaid as a peer dependency.
  • Works anywhere. Vanilla JS, React, Next.js, TanStack Start, Svelte, plus an <animated-mermaid> web component for Vue, Angular, Astro or plain HTML.
  • Exports. An animated SVG that plays on its own inside <img> tags and GitHub READMEs, a GIF for Slack, Teams and slides, and a PNG of the finished diagram.
  • Controllable. play, pause, restart, seek(ms), looping, and play-when-visible.
  • Accessible. Honors prefers-reduced-motion by default: readers who turn motion off get the finished diagram straight away. (That is why the demos below show no Replay button on those devices.)

It is tested with Mermaid 12 on flowcharts, sequence, state and class diagrams. Other diagram types fall back to a top-to-bottom reveal.

Install

npm i animate-mermaid mermaid

Quick start

The shortest path is renderAnimated. Give it a container and Mermaid source, and it renders and animates in one go.

import { renderAnimated } from 'animate-mermaid'
 
const ctrl = await renderAnimated(
  document.getElementById('diagram'),
  `
flowchart LR
  A[Client] --> B[API] --> C[(DB)]
`,
  { loop: true },
)
 
ctrl.pause()
ctrl.seek(800) // jump to 800 ms
ctrl.play()

Already rendering Mermaid yourself? Animate the SVG you have:

import { animate } from 'animate-mermaid'
 
const ctrl = animate(document.querySelector('#my-diagram svg'))

Framework setup

import { AnimatedMermaid, useAnimatedMermaid } from 'animate-mermaid/react'
 
export function Architecture({ source }: { source: string }) {
  return <AnimatedMermaid chart={source} order="flow" autoplay="visible" />
}
 
// or the hook, when you want the controller
function WithHook({ source }: { source: string }) {
  const { ref, controller, error } = useAnimatedMermaid(source, { loop: true })
  return <div ref={ref} />
}

The React entry ships with "use client", so it drops into Next.js App Router pages. Mermaid is imported lazily inside an effect, so server rendering never touches the DOM. The same component works in TanStack Start; this blog runs on it.

Options worth knowing

You rarely need more than a couple of these.

OptionDefaultWhat it does
order'flow''flow' follows edges, 'position' reveals top to bottom, 'together' reveals everything at once
nodeEffect'pop''pop', 'fade', 'slide' or 'none'
edgeEffect'draw''draw', 'fade' or 'none'. Dashed and dotted edges always fade
nodeDuration / edgeDuration450 / 500Milliseconds per item
stagger120Gap between items in position order
loop / loopHoldfalse / 1500Replay forever, holding the finished diagram between runs
autoplaytruetrue, false (wait for play()), or 'visible' (start on scroll into view)
respectReducedMotiontrueSkip the animation for reduced-motion users
theme / transparentnone / falseBuilt-in palette name or your own colors. transparent skips the background (since 0.2)
edgeMotion'none''dash' or 'dot': keep edges moving after they appear (since 0.2)
nodeStyle'default''2d' flat nodes or '3d' raised blocks (since 0.3)

order: 'flow' is the one that makes the difference. A top-to-bottom reveal looks nice, but following the edges is what turns a picture into an explanation.

What’s new in 0.2 and 0.3

The first release animated Mermaid’s own look. The next two releases add three things that change how a diagram looks, not just how it arrives: themes, edge motion and node styles. They work together, and all of them work with every framework entry point.

npm i animate-mermaid@latest

Themes

Mermaid’s built-in themes are fine, but they rarely match the site around them. The new theme option takes one of 15 palettes built from the original themes’ published colors:

zinc-light, zinc-dark, tokyo-night, tokyo-night-storm, tokyo-night-light, catppuccin-mocha, catppuccin-latte, nord, nord-light, dracula, github-light, github-dark, solarized-light, solarized-dark, one-dark.

The theme sets the background, node fill and border, edge color, arrowheads and edge labels. Here is the request flow from the top of the post in tokyo-night:

theme: 'tokyo-night'
renderAnimated(el, source, { theme: 'tokyo-night' })

To follow a site’s light and dark mode, pick the matching pair and pass transparent: true, so the diagram sits on the page background instead of painting its own. That is what the next demos on this page do with zinc-light and zinc-dark; switch the site theme and they redraw.

const dark = useIsDarkMode() // however your site tracks it
<AnimatedMermaid chart={source} theme={dark ? 'zinc-dark' : 'zinc-light'} transparent />

You can also bring your own colors. Only bg and fg are required; the rest are mixed from those two.

renderAnimated(el, source, {
  theme: { bg: '#0b1020', fg: '#e2e8f0', accent: '#38bdf8' },
})

Rendering Mermaid yourself? themeConfig('dracula') returns the matching Mermaid config, and THEMES lists every palette.

Edge motion

A finished diagram is still a still image. Once the reveal is over, the reader cannot tell which way an edge points without hunting for the arrowhead. edgeMotion keeps the edges moving toward their targets after they appear.

edgeMotion: 'dash'. Dashes march toward each arrowhead.
edgeMotion: 'dot'. A dot travels along each edge.
renderAnimated(el, source, {
  edgeMotion: 'dash', // or 'dot'
  edgeMotionDuration: 1000, // one cycle in ms (default 1000 dash, 2000 dot)
  edgeMotionColor: '#38bdf8', // default: theme accent, else each edge's color
})

dash reads as “data flowing”, which suits pipelines and queues. dot reads as “one thing moving”, which suits requests and messages. Both are hidden for readers with prefers-reduced-motion, and both survive the animated SVG export. GIF exports keep moving through the final hold instead of freezing on one frame.

Node styles

Mermaid’s newer look gives nodes soft drop shadows. nodeStyle lets you go flatter or deeper:

  • '2d': crisp, flat nodes with Mermaid’s shadows removed. Good for dense diagrams and print.
  • '3d': raised blocks. Each node gets an extruded edge in a darker shade of its border, a soft shadow and a top-lit fill. It works on any shape (boxes, diamonds, circles, cylinders, sequence actors) and adapts to light and dark themes.
nodeStyle: '3d' on every shape
nodeStyle: '2d' on the same diagram
renderAnimated(el, source, { nodeStyle: '3d' })
 
// Rendering Mermaid yourself? Style the SVG before animating it
import { animate, styleNodes } from 'animate-mermaid'
const restore = styleNodes(svg, '3d') // returns a function that undoes it
animate(svg)

All together

Themes, edge motion and node styles combine freely. This is the setup I now use across the blog: zinc to match the site, pop for nodes, marching dashes and 3D blocks.

palette zinc + nodeEffect 'pop' + edgeMotion 'dash' + nodeStyle '3d'
<AnimatedMermaid
  chart={source}
  theme={dark ? 'zinc-dark' : 'zinc-light'}
  transparent
  nodeEffect="pop"
  edgeMotion="dash"
  nodeStyle="3d"
  autoplay="visible"
/>

Smaller fixes

  • Several themed diagrams on one page. Mermaid’s config is global, so two diagrams rendering at once could swap themes. Renders now run one at a time, each with its own config.
  • Smaller package. The published build dropped its source maps, going from 107 kB to 32 kB.
  • CommonJS. All CommonJS entries share one copy of the engine, so animation IDs no longer clash.

The full list is in the changelog.

Export: SVG, GIF and PNG

Animation is only half the job. Most diagrams end up somewhere that cannot run your JavaScript: a GitHub README, a Notion page, a Slack thread, a slide.

import { renderAnimated, toSvgString, toGif, toPng, download } from 'animate-mermaid'
 
const ctrl = await renderAnimated(el, source)
 
download(toSvgString(ctrl.svg), 'diagram.svg') // animated SVG, plays inside <img>
download(await toGif(ctrl), 'diagram.gif') // animated GIF
download(await toPng(ctrl.svg), 'diagram.png') // final frame

A few details that matter in practice:

  • Animated SVG is the smallest and sharpest. The keyframes live inside the file, so it plays in browsers, <img> tags and GitHub READMEs.
  • GIF is rendered frame by frame, not screen recorded, so the timing is exact even on a slow laptop. A 3 second flowchart at 20 fps is about 60 frames and roughly 400 KB. Every frame shares one palette from the finished diagram, so colors do not flicker. The encoder only loads when you call toGif.
  • PNG captures the finished diagram, or any moment with frame: ms.

Every demo on this page has SVG and GIF buttons. Try them: the files come straight out of your browser.

Sharing to Slack, Teams or WhatsApp

shareFile opens the system share sheet, and falls back to a download where sharing is not supported.

import { toGif, shareFile } from 'animate-mermaid'
 
// click 1: build the GIF (a few seconds)
const gif = await toGif(ctrl)
 
// click 2: share it
shareButton.onclick = () => shareFile(gif, { filename: 'diagram.gif', title: 'Architecture' })

Browsers only allow the share sheet for a short time after a click, so build the GIF on one click and share it on the next.

Real world examples

Here is where I actually reach for it. Each one is a live demo, written as plain Mermaid.

1. Onboarding docs: how a request moves through your system

New engineers do not need every service on day one. They need the path a request takes. A flow-ordered reveal walks them through it in the same order you would explain it at a whiteboard.

Checkout service: from click to confirmation email

Subgraphs fade in just before their contents, so the reader sees “Edge” and “Services” as zones before the boxes fill them.

2. Pull requests and design docs: explaining a sequence

Sequence diagrams are where a static image hurts the most. Ten arrows between four lifelines, all visible at once, and the reader has to trace them by hand. With order: 'position' they arrive one message at a time.

OAuth 2.0 authorization code flow with PKCE

Export it as an animated SVG and drop it into the PR description. GitHub renders it inside an <img>, so reviewers get the animation without running anything.

3. Teaching: state machines

State diagrams are cyclic, which makes them hard to read from a still image. Watching the transitions draw in order shows the happy path first and the retries after.

Lifecycle of a background job

4. AI and agent workflows

Agent pipelines branch and loop back, and that loop is the part people miss. An animated diagram makes the “go back and try again” step impossible to overlook.

A tool-using agent loop

5. Slides and Slack updates

For a weekly update or a conference talk, I write the diagram in Mermaid, hit GIF, and paste the file into Slack or Keynote. No screen recording, no video editor, and the GIF is small enough to post without anyone noticing the upload.

Release pipeline, ready to export as a GIF

6. Using it with a coding agent

The repo also ships an Agent Skill: a SKILL.md plus a headless CLI. Install it once and a coding agent such as Claude Code can turn a Mermaid file into an animated SVG or GIF for you, or wire the library into your app with the right snippet for your framework.

cp -r skills/animate-mermaid ~/.claude/skills/
cd ~/.claude/skills/animate-mermaid/scripts && npm install

The CLI works on its own too:

node skills/animate-mermaid/scripts/animate.mjs diagram.mmd -o diagram.svg -o diagram.gif --loop

Things to know

  • Exported SVGs use the viewer’s default fonts unless you inline a web font.
  • Safari can refuse to rasterize HTML labels (<foreignObject>) to PNG or GIF. If that happens, render with mermaidConfig: { htmlLabels: false }.
  • A PNG cannot animate. Use the SVG or GIF, or call renderFrame to build your own frames.
  • Firefox desktop has no share sheet, so shareFile downloads the file instead.

Try it

npm i animate-mermaid mermaid

The source, examples for plain HTML, React and Svelte, and the agent skill are on GitHub. The package is on npm. It is MIT licensed, and issues and pull requests are welcome.

If you write docs, teach, or just explain systems for a living, give your next diagram a few hundred milliseconds of motion. It is surprising how much easier it is to follow.