Motion SVG reference
A Motion SVG is a normal SVG file with one extra block that describes how it moves and reacts. It always renders as a static image anywhere SVG works; with the Motion Forge runtime it plays, responds to clicks, hovers, pointer position and app data.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<title>Bouncing ball</title>
<ellipse id="shadow" cx="100" cy="172" rx="34" ry="7" fill="#d9d4ca"/>
<circle id="ball" cx="100" cy="60" r="26" fill="#ff5a1f"/>
<metadata type="application/motion+json"><![CDATA[
{
"states": {
"idle": {
"duration": 900,
"loop": true,
"animate": {
"#ball": { "translateY": { "0%": 0, "50%": { "value": 86, "ease": "in" }, "100%": { "value": 0, "ease": "out" } },
"scaleY": { "0%": 1, "48%": 1, "55%": 0.8, "62%": 1 }, "origin": "bottom" },
"#shadow": { "scale": { "0%": 0.6, "50%": 1, "100%": 0.6 }, "opacity": [0.4, 1, 0.4] }
}
}
}
}
]]></metadata>
</svg>Artwork rules
- Write ordinary SVG. Give every element you animate an
id(or a sharedclassfor groups of similar elements). - Always set
viewBox. Add a<title>as the first child (it becomes the accessible label). - Anything you rotate or scale as a unit should be a
<g>; animate the group. - Put the motion block last, inside
<metadata type="application/motion+json"><![CDATA[ … ]]></metadata>. CDATA means you never escape<,&or quotes. - Supported: shapes, paths, groups,
<use>, text, gradients, patterns, clip paths, masks, filters (blur, drop shadow, …), embeddeddata:images,<style>rules andstyle=""(folded into attributes). Removed for safety: scripts, event handlers,<foreignObject>, external URLs, SMIL<animate>.
The motion block
{
"version": 1, // optional
"title": "…", // optional, overrides <title>
"initial": "idle", // optional, defaults to the first state
"inputs": { … }, // values your app or interactions set
"states": { "name": { … } }, // the state machine
"on": { "reset": "idle" }, // events handled in every state
"transition": 250, // default blend between states (ms) or { "blend": 250, "ease": "out" }
"bind": { … }, // inputs drive properties continuously
"interactions": [ … ], // click/hover/press/pointer/drag/appear, no host code needed
"layers": { "blink": { "initial": "…", "states": { … } } } // extra state machines running in parallel
}States
"waving": {
"duration": 1600, // ms or "1.6s"; inferred from ms keyframes; 1000 if only % keys; 0 for poses
"loop": true, // true = forever, or a repeat count; default plays once
"alternate": false, // ping-pong every other loop
"ease": "ease-in-out", // default easing for this state's keyframes
"animate": { // CSS selector → properties
"#arm": { "rotate": [0, -40, -10, -40, 0], "origin": "15% 90%" },
".dot": { "translateY": { "0%": 0, "30%": -10, "60%": 0 }, "stagger": 120 }
},
"on": { "wave": "waving", "done": { "to": "idle", "blend": 400, "ease": "spring" } },
"when": { "level > 80": "alarm", "!enabled": "off" }, // conditions over inputs, checked continuously
"next": "idle", // where to go when this (non-looping) state finishes
"emit": "waved", // event your app receives when this state starts
"allowOverflow": true, // this state leaves the frame on purpose (silences the overflow lint)
"set": { "progress": 0 } // inputs to set when this state starts (e.g. a reset state)
}Transitions anywhere (on, when, next, top-level on) are a state name or { "to": "idle", "blend": 400, "ease": "spring" }.
- Pose states hold values without a timeline:
"open": { "animate": { "#lid": { "rotate": -35 } } }. The transition blend animates into them, so poses + transitions give you smooth UI states cheaply. - Switching states always blends from whatever is on screen (default 250ms,
outeasing) so interruptions never jump. - Properties a state doesn't animate return to their resting value (the value in the SVG) during the blend.
- Exception: if a property was at rest and the new state gives it an explicit
0%keyframe, it starts exactly there (so a stroke that draws on never flashes fully drawn first). - When the player starts, it settles into the state that matches the initial inputs without playing the transitions on the way (mounting a like button with
liked: trueshows it liked, silently).
Keyframes
Any property accepts:
| Form | Meaning |
|---|---|
42 |
Hold 42 for the whole state. The transition into the state animates to it. |
[0, 20, 0] |
Evenly spaced keyframes over the duration. |
{ "0%": 0, "40%": 20, "100%": 0 } |
Percent of duration. "from"/"to" also work. |
{ "0": 0, "250ms": 20, "0.6s": 0 } |
Absolute times (ms by default). |
{ "value": 20, "ease": "spring" } |
Any keyframe value can carry the easing used to arrive at it. |
If there is no 0% key, the animation starts from the element's resting value. After the last key the value holds. { "value": v, "ease": "hold" } jumps at the end of a segment instead of tweening, which is how you reset something invisibly inside a loop.
Group options (next to the properties)
"origin": pivot for rotate/scale/skew."center"(default: the element's own center),"left top","bottom","50% 100%"(of the element's box), or absolute coordinates"120 80"in the element's parent space (the artboard, unless it sits inside transformed groups). One origin per element across all states and layers; if two moves need different pivots, wrap the element in a<g>and give each its own."stagger": ms offset between each element the selector matches (in document order). In loops the offset wraps, which is how you build loaders."delay": ms before this group starts. In loops it wraps too, so it works as a phase offset."ease": default easing for this group."curve": "smooth": flow through the keyframes (Catmull-Rom) instead of easing to a stop at each one. Use it for arcs, figure-eights, floating and swaying paths.
Properties
| Property | Values | Notes |
|---|---|---|
translateX, translateY |
number (user units) | Moves any element. Use these, not x/y, for motion. |
rotate |
degrees | Around origin. |
scale, scaleX, scaleY |
number | Around origin. scale multiplies scaleX/scaleY. |
skewX, skewY |
degrees | |
opacity, fill-opacity, stroke-opacity |
0..1 | |
fill, stroke, stop-color, flood-color |
any CSS color | Mixed in OKLab, so fades stay vivid. "none" = transparent. |
stroke-width, stroke-dashoffset |
number | |
draw |
0..1, or a [start, end] pair as a keyframe value |
Draws a stroke on/off (path, line, circle, rect, ellipse, polyline, polygon). "draw": [0, 1] animates 0→1; for a moving segment use pairs: { "0%": [0, 0.1], "100%": [0.9, 1] }. Mark strokes that rest hidden with data-draw="0" on the element (static renders respect it too). |
d |
path data | Morphs between any two paths, even with different point counts. |
points |
point list | Polygon/polyline morph (same number of points). |
| geometry | number | cx cy r rx ry x y width height x1 y1 x2 y2 on the elements that have them. |
stdDeviation, dx, dy, offset |
number | Filter blur/shadow offset, gradient stop offset. Target the filter primitive/stop by id. |
font-size, letter-spacing |
number | |
text |
string | Steps text content (for counters use bind with a template). |
camelCase aliases work (strokeWidth, fillOpacity, stopColor, …).
Easing
linear, ease, ease-in, ease-out, ease-in-out, stronger in, out, in-out, snappy, anticipate, back, back-in, elastic, bounce, spring, spring-soft, spring-bouncy, hold, plus cubic-bezier(x1, y1, x2, y2), spring(stiffness, damping, mass), steps(n). Springs are fitted to the keyframe's duration so they always land on time.
Good defaults: out for things arriving, in for things leaving, in-out for things moving between two places, spring for UI that should feel physical, linear only for constant rotation or progress.
Inputs
"inputs": {
"progress": { "type": "number", "min": 0, "max": 100, "default": 0, "smooth": 300 },
"liked": false, // shorthand boolean
"lookX": { "type": "number", "min": -1, "max": 1, "default": 0, "smooth": 150 }
}smooth (ms) eases the displayed value toward new values, so data changes glide instead of jumping. "smooth": "spring" or "spring(stiffness, damping)" uses a physical spring that can overshoot (needles, gauges, sliders).
Conditions (when) test the target value the moment it is set: "progress >= 100". Prefix with ~ to test the displayed (smoothed) value instead, so a celebration waits for the bar to actually arrive: "~progress >= 100". Conditions support numbers, true/false, < <= > >= == !=, && || !, + - * / % and parentheses.
Bindings: inputs drive properties
"bind": {
"#needle": { "rotate": { "input": "progress", "from": -120, "to": 120 }, "origin": "50% 90%" },
"#bar": { "width": { "input": "progress", "map": { "0": 0, "50": 90, "100": 200 } } },
"#face": { "fill": { "input": "progress", "map": { "0": "#3ecf8e", "70": "#ffb020", "100": "#ff4d4f" } } },
"#label": { "text": "{progress}%" }
}from/to map the input's min..max. map takes input values as keys, and any stop can be { "value": v, "ease": "out" }. Text templates (on <text> or <tspan>) take {name} or {name:1} (decimal places). Bindings override state animation for the same property; add "add": true to a numeric binding to add it on top instead (a head that tilts toward the pointer while it also bobs).
Interactions (declared in the file, no host code)
"interactions": [
{ "on": "click", "target": "#heart", "toggle": "liked" },
{ "on": "click", "target": "#button", "send": "press" },
{ "on": "hover", "target": "#card", "set": "hovered" }, // boolean input held while hovered
{ "on": "hover", "target": "#card", "send": "enter", "leave": "exit" },
{ "on": "press", "target": "#key", "set": "pressed" },
{ "on": "pointer", "x": "lookX", "y": "lookY" }, // pointer position over the artwork → input range
{ "on": "drag", "target": "#gauge", "x": "value" }, // drag across the target's box to set an input
{ "on": "drag", "target": "#knob", "x": "value", "within": "#track" }, // map positions to another element's box
{ "on": "appear", "send": "intro" }, // fires once when scrolled into view
{ "on": "click", "target": "#reset", "set": { "progress": 0 } }
]Clickable targets (including the SVG root) become keyboard-focusable buttons automatically; boolean toggles announce aria-pressed. Press targets accept Enter/Space down and up, and release on blur. Hover targets also respond to focus/blur. Drag targets become sliders (arrow keys, Home/End). pointer maps over the whole artwork (or within) and resets inputs to their defaults when the pointer leaves.
Layers
Layers are extra state machines that run at the same time as the main one: a character blinks while it waves. Later layers override earlier ones for the same property, and bindings override everything (the checker warns when that hides something). Give a layer "add": true to add its numeric/transform values on top instead, e.g. an idle sway layer that keeps swaying while the main state rotates the same group.
"layers": {
"blink": { "states": { "open": { "duration": 3800, "loop": true, "animate": { ".eye": { "scaleY": { "0%": 1, "92%": 1, "95%": 0.1, "98%": 1 } } } } } }
}How transforms compose
Animated translateX/Y, rotate, scale, skew are applied around the element's origin, on top of any transform the element already has in the SVG (in the parent's coordinate space). Nested groups compose naturally: animate the arm group, and the hand group inside it too.
Using it
<motion-forge src="/like.svg" inputs='{"liked":true}'></motion-forge>
<script type="module">
import 'https://cdn.jsdelivr.net/npm/motion-forge/dist/element.js';
const el = document.querySelector('motion-forge');
el.addEventListener('statechange', e => console.log(e.detail.to));
</script>import { MotionForge } from 'motion-forge/react';
import like from './like.svg?raw';
<MotionForge svg={like} inputs={{ liked }} onEvent={e => e.type === 'emit' && track(e.name)} />import { mount } from 'motion-forge';
const anim = mount(document.querySelector('#slot'), svgText);
anim.send('wave'); anim.set('progress', 72);Checklist before you ship an animation
motion-forge check file.svghas 0 errors and you understood every warning. Usecheck --strict file.svgto fail CI on warnings as well.motion-forge preview file.svgand look at the PNG: every state row, every input sweep. Things should stay inside their frames, rest poses should look finished, and loops should end where they start.- The preview exercises each event from each state that handles it (including layer-wide handlers), and both directions of every boolean toggle. These scenarios start directly in the stated source state; they do not prove every possible path is reachable. Conditions use best-effort inferred inputs. Numeric sweeps hold the selected/watching main state so you can inspect its binding. For full paths, interruptions and combinations,
motion-forge record file.svg --send wave@600 --set level=90@1500prints an event log and writes a PNG grid (--out x.giffor people). Script actions run at their exact timestamps; images sample at the selected frame rate. - Motion has purpose: one clear idea per state, 150-400ms for UI feedback, 1-4s for ambient loops, easing that matches physics (
outarriving,inleaving).
Runtime and tooling limits
- The loader sanitizes a supported SVG subset, not every possible editor export. Scripts, external URLs, SMIL and unsupported elements are removed. Review diagnostics and the rendered result. Source is limited to 2 MB and XML nesting to 128 levels; invalid roots produce an empty safe SVG with errors.
- Text precision (
{value:2}) accepts 0–100 decimal places. Invalid precision is diagnosed. - Recordings accept positive durations up to 20,000ms and frame rates up to 120fps. Script times must be non-negative and before the recording end. Malformed script values and invalid numeric options fail with errors.
- Raster output is limited to 32 megapixels and 16,384px per side. Use
preview --state name --cell 120for large files. Preview accepts 1–24 frames per state;--frames 1also works for input sweeps. - The runtime follows changes to
prefers-reduced-motionwhen set toauto(the default). SVG viewBox clipping is the default; useoverflow="visible"on the SVG for intended exits.allowOverflowonly suppresses the lint warning. - React SSR prefixes IDs and accessible references per instance. React
onErrorreports fetch and validation failures. The web component accepts initial values through itsinputsattribute; set them before connection to start in the settled state without animating there. - The playground can open/download SVGs, save a local browser draft, pause/scrub/restart the main state, and show a bounded event log. Scrubbing inspects a state; Play resumes state-machine behavior. It does not edit keyframes visually.
Agent workflow
This is the skill that npx motion-forge init installs. It’s written for coding agents, and it doubles as a good checklist for humans.
Motion Forge
A Motion SVG is plain SVG plus a JSON motion block: a state machine, keyframes, inputs, bindings and interactions. You write it as text, the CLI shows you what it looks like, and the runtime plays it in any web app.
Full format: reference.md in this folder (or run npx motion-forge docs).
Workflow (follow it every time)
- Start from something close. Run
npx motion-forge list. If a preset is near what the user wants,npx motion-forge add <preset> --dir <assets dir>and adapt it. Otherwisenpx motion-forge new <path>.svg. - Draw the artwork first. Clean SVG with a
viewBox, a<title>, and ids on everything that moves. Group parts that move together (<g id="arm">). Keep 8-12% padding inside the viewBox so scale-ups and overshoot don't clip. - Design the states before the keyframes. Name them after what the user sees (
idle,hover,loading,success). Decide how you get between them: events (on), input conditions (when),nextafter a one-shot, or interactions in the file. - Write the motion block. Prefer poses + blends for UI states, keyframed loops for ambient motion, bindings for data. Set
originfor anything that rotates or scales around a joint. - Check:
npx motion-forge check <file>. Fix every error. Read the warnings; loop seams, overflow and static channels are almost always real bugs. Usecheck --strict <file>when CI should reject warnings. - Look:
npx motion-forge preview <file> --out /tmp/<name>.png, then open the PNG with your image-reading tool. Each state is a row of frames over time; every event and boolean toggle gets a "flow" row played through the real state machine (blends,next, conditions); each bound input gets a sweep row. If the app has a dark or colored background, add--bg '<color>'so you judge contrast on the real surface. Judge it like a motion designer: silhouettes readable, spacing even, nothing clipped, rest poses complete, loops seamless, no flashes between states. - Play custom flows:
npx motion-forge record <file> --send <event>@600 --set <input>=<value>@1200prints an event log (state changes, emits) and writes a PNG grid of frames over time to read. Include reversal/interruption and reset paths. Preview flow rows start directly in each source state and exercise both boolean directions; they are not exhaustive reachability tests. Use--out x.gifonly for humans. - Iterate until the preview looks intentional. Then wire it in (below) and tell the user which events/inputs the file exposes.
Wiring it into an app
- React:
import { MotionForge } from 'motion-forge/react'then<MotionForge svg={source} inputs={{ progress }} onEvent={…} />(src="/file.svg"also works;svgrenders on the server). - Anything else:
import 'motion-forge/element'then<motion-forge src="/file.svg"></motion-forge>, withel.send(event),el.set(input, value)andstatechange/emitDOM events. - Vanilla:
import { mount } from 'motion-forge';mount(el, svgText)returns{ send, set, goto, play, pause, destroy }. - Install:
npm i motion-forge.
Taste rules
- One idea per state. UI feedback 150-400ms; attention loops 1-4s; nothing jittery under 60ms.
- Arrivals use
out/spring; departures usein; anticipation before big moves (anticipate, or a small counter-move keyframe). - Overlap and stagger (20-80ms) make groups feel alive; identical timing looks mechanical.
- Squash and stretch around the contact point (
origin: "bottom"), not the center. - Respect the palette the user already has. Pull colors from their CSS/theme when you can.
- Loops must end exactly where they start (the checker flags seams). Blinks, breathing and floating belong in
layersso they keep running during other states. - Celebrate when the value the user sees arrives:
"~progress >= 100"waits for smoothed values;"progress >= 100"fires instantly. - Strokes that should start hidden get
data-draw="0"in the SVG. A bare value in a state holds it; the transition animates into it.
Things that are not supported
Arbitrary JavaScript, external images/fonts/URLs, SMIL, skeletal bones, and 3D. Text renders with the host's fonts; outline text into paths when the exact typeface matters.