Code-Driven Stickman Animation: A Practical Guide to Consistent, Reproducible Video Production
This article explains why asking a large language model to draw animation directly leads to unstable proportions, style drift, and costly regeneration, and how to fix it by splitting the work: the model acts as director while deterministic code handles the artwork. It walks through packaging domain knowledge into a reusable Skill (`stickman-animator`), locking bone lengths in a single rig file, driving poses with pure time-based joint-angle functions, separating camera zoom from character scale, and rendering frames headlessly for local MP4 export. It also includes self-check rules, a cost comparison against generative video, and the boundaries where this approach does not fit.
1. The Problem: Why LLM-Generated Animation Keeps Breaking
Ask a coding agent to “build a 15-second stickman animation webpage” and it will deliver something fast. Open the page and the character usually looks fine. Keep iterating, though, and problems pile up:
- Change one line of dialogue: the model rewrites the whole file and the existing motion changes with it.
- Add a close-up: the character’s proportions shift along with the camera zoom.
- Generate a few variants: every take has a different body weight and different arm and leg lengths.
The failures fall into three categories:
- Out-of-control proportions: shoulder width, leg length, and head diameter have no shared baseline, so everything depends on the model’s feel at generation time.
- Style drift: one run draws fingers or shoes, the next reverts to plain lines, and the same character is not the same character from shot to shot.
- Expensive regeneration: a one-line copy change triggers a full-file rewrite, the skeleton drifts, and you are back to rerolling until something acceptable appears.
The root cause is that handing “draw an animation” straight to a language model means relying on probabilistic sampling. Each generation is an independent output, and the model never actually holds a quantitative constraint like “this character’s bones are this long.”
A better division of labor is to let the model be the director and turn the artwork into deterministic code:
- Model: read the script, decide the shot list, action sequence, and dialogue.
- Code: convert joint angles into joint coordinates and draw every frame.
One or two proportion glitches during prototyping are tolerable. But character consistency is the core selling point of this kind of content, and once you go into batch production, any single drift is a quality incident. The domain knowledge therefore has to be solidified into reusable, verifiable rules before production starts.
2. The Solution: Package Domain Knowledge as a Reusable Skill
Coding agents have recently gained a “skill” style extension mechanism. The core idea is to distill a task’s domain knowledge into a standalone directory: usually one instruction file that tells the model when to use it and how to constrain output, plus a few executable scripts. When the tool detects a matching task in the conversation, it loads the skill automatically, and the same skill can be reused across projects and across conversation turns.
This mechanism is not exclusive to any single vendor. Specific specs differ between platforms, but the general form of “domain instructions plus executable scripts” is enough to support the practice in this article, and the same approach transfers to other comparable coding agents.
This article implements the whole ruleset as a local skill named stickman-animator:
stickman-animator/├── SKILL.md # use cases, hard constraints, tunable parameters├── rig.js # skeleton baseline: bone lengths, line width, head ratio├── engine.js # skeleton solver and Canvas drawing├── actions.js # action library: pure functions from time to joint angles├── export-mp4.js # headless frame-by-frame rendering and video encoding└── scenes/ # shot configs (scene JSON) and finished HTML
The frontmatter of SKILL.md uses name and description to state when to use the skill; the body defines how to use it and what must not be done:
---name: stickman-animatordescription: Generate frame-by-frame stickman animation with code. Ships a skeleton baseline and an action library, supports lossless local MP4 export; suited to explainer videos, product demos, and short-form video intros. Use when a stickman animation is needed.---## Capabilities- Generate HTML animation from a shot list that plays directly in the browser (Canvas rendering)- Render frame by frame locally in headless mode and encode to MP4 with a command-line encoder## Hard constraints1. All bone lengths, line widths, and head ratios must be read from RIG in rig.js; hardcoding sizes anywhere else is forbidden.2. All actions must call functions in actions.js; writing per-frame coordinates by hand is forbidden.3. Camera changes may only modify camera parameters (zoom, pan); modifying the skeleton baseline is forbidden.4. Before export, self-check that render timestamps are invoked exactly, and confirm no frames are dropped before encoding.## Tunable parametersShot duration, action sequence, subtitle copy and bilingual pairing, frame dimensions and frame rate.
The key to this layer is enforceable constraints. Descriptions like “the character’s proportions should look harmonious” or “the motion should feel natural” cannot be executed, so the model can only improvise. Clauses like “bone lengths may only be read from RIG” or “the camera may only change zoom and pan” can be validated directly in code, and every model output has to comply.
3. How It Works: Lock the Skeleton Baseline, Drive Motion With Single-Joint Angles
3.1 A skeleton is a polyline, a joint is an angle
A stickman’s torso and limbs are essentially a few polylines with rounded endpoints; the head is a perfect circle, and the eyes are small dots placed inside it at a fixed ratio. Since the body is a set of line segments, two rules follow:
- Polyline length is determined by bone length, not by the model. The same character has identical limb lengths at every moment and under every camera.
- Each joint is controlled by exactly one angle. Defining an action means giving a set of functions for how angles change over time.
The solver uses classic forward kinematics: given each bone length and the angle between adjacent segments, walk the joint chain and accumulate coordinates.
This representation also yields a set of skeleton invariants that can be verified automatically before and after rendering:
| Invariant | Expression |
|---|---|
| Shoulder-to-elbow distance constant | distance(shoulder, elbow) = upper arm length |
| Wrist chain constant | distance(hand, elbow) = forearm length |
| Hip-knee-ankle constant | distance(hip, knee) and distance(knee, ankle) equal thigh and shin lengths |
| Head radius constant | head radius is always RIG.headR |
As long as joint coordinates are computed from bone lengths and angles, these invariants always hold. If the model tries to “draw it a bit longer” or “a bit shorter,” the solver overwrites the attempt.
3.2 Solving and drawing the skeleton
engine.js handles both solving and drawing:
// rig.js: the single skeleton baseline for the whole filmexport const RIG = Object.freeze({headR: 14, headR2: 9, // head radius, distance from brow/eye center to top of headneck: 8, torso: 52, // neck length, torso lengthupperArm: 32, foreArm: 30,thigh: 38, shin: 38,shoulderW: 18, // spacing of the two joints in side view (reads as shoulder width)hipW: 8, // lateral hip offsetlineWidth: 6,});const D = Math.PI / 180;const pt = (o, len, deg) => ({ // screen coordinates, y axis points downx: o.x + len * Math.cos(deg * D),y: o.y + len * Math.sin(deg * D),});const kneeBend = a => 4 + 30 * Math.max(0, -Math.cos(a)); // knees only bend backward// input: angle parameters a (produced by an action function); output: all joint pointsexport function solve(a) {const s = {}, hip = { x: 0, y: 0 };const spine = 90 + a.lean; // torso direction, leaning forward around the hipconst neck = pt(hip, RIG.torso, spine);const head = pt(neck, RIG.neck, spine);const shF = pt(hip, RIG.shoulderW / 2, spine); // front shoulderconst shB = pt(hip, -RIG.shoulderW / 2, spine); // back shoulderconst arm = (sh, deg) => {const el = pt(sh, RIG.upperArm, deg);return { s: sh, e: el, h: pt(el, RIG.foreArm, deg + a.elbow) };};s.armF = arm(shF, spine + a.arm); // front arms.armB = arm(shB, spine + a.armB); // back armconst leg = (ph) => {const hp = { x: ph, y: hip.y };const kn = pt(hp, RIG.thigh, 90 + a.legs);return { h: hp, k: kn, f: pt(kn, RIG.shin, 90 + a.legs + kneeBend(a.legs)) };};s.legF = leg(hip.x + RIG.hipW / 2);s.legB = leg(hip.x - RIG.hipW / 2);return { hip, neck, head, ...s };}// input: a solved skeleton; output: draws to a 2D contextexport function draw(ctx, s, a) {ctx.lineCap = ctx.lineJoin = 'round';ctx.lineWidth = RIG.lineWidth;ctx.strokeStyle = a.color || '#222';const seg = (p, q) => { ctx.beginPath(); ctx.moveTo(p.x, p.y); ctx.lineTo(q.x, q.y); ctx.stroke(); };for (const L of [s.armB, s.legB]) { seg(L.s || L.h, L.e || L.k); seg(L.e || L.k, L.h || L.f); }seg(s.hip, s.neck);for (const L of [s.legF, s.armF]) { seg(L.h || L.s, L.k || L.e); seg(L.k || L.e, L.f || L.h); }ctx.beginPath(); ctx.arc(s.head.x, s.head.y, RIG.headR, 0, 2 * Math.PI); ctx.stroke();ctx.beginPath(); ctx.arc(s.head.x, s.head.y - RIG.headR2, 2, 4.4); ctx.stroke(); // eye}
In side view the torso and limbs lie roughly in one plane, so a single set of angles drives the whole character. The knee and elbow bend directions are fixed, which prevents the model from producing poses that violate human anatomy.
3.3 Action functions: time in, no randomness
Every action is a pure function: input is normalized time u (0 to 1 within the current act), output is a set of joint angles. A pure function means the same timestamp always maps to the same pose, and rendering any frame yields an identical result. That is the foundation of “re-exportable and reproducible.”
// actions.js: u is normalized time within the current actconst PI2 = Math.PI * 2;export const idle = u => ({lean: 0, arm: 8, armB: -6, elbow: 8, legs: 0,bob: 1.5 * Math.sin(PI2 * u * 2), // subtle breathing motion});export const walk = u => {const p = PI2 * u * 2; // exactly 2 strides across the actreturn {lean: 4, arm: 22 * Math.sin(p), armB: -22 * Math.sin(p),elbow: 12, legs: 28 * Math.sin(p),bob: 2 * Math.abs(Math.cos(p)), // body rises and falls with the stride};};export const wave = u => ({lean: -2, arm: 150, armB: -8, elbow: 20, legs: 0,handWave: 18 * Math.sin(PI2 * u * 3), // waving hand});
Three lessons from practice:
- End on a whole cycle: the animation duration should be an integer multiple of the action period, for example 2 strides inside a 15-second piece. Start and end poses then match, so camera cuts do not produce a visible “step skip.”
- Interpolate angles between actions: when switching actions, ease between the two action functions’ outputs, e.g.
(1 - t) * a1[k] + t * a2[k]wheretis transition progress, so the pose never jumps. - Translation changes position only, never pose: when the character moves across the frame, translate the whole coordinate set and never scale it. The bone-length-to-world ratio stays constant.
3.4 Shots and camera: scale the frame, not the character
The character skeleton is defined in “world coordinates,” and the camera is just a transform from world to screen coordinates. Browser playback and export use the same camera definition, so what you see is what you get.
// scenes/act.json: camera and actions are configured only here{"fps": 60, "duration": 15,"camera": { "baseZoom": 1.6, "zoomEase": "linear" },"acts": [{ "start": 0, "action": "walk", "from": 1.0, "to": 1.5,"lines": [{ "cn": "省下一笔外包", "en": "No outsourcing budget" }] },{ "start": 5, "action": "wave", "from": 1.5, "to": 1.8,"floaters": [{ "text": "-$", "t": 1.0 }],"lines": [{ "cn": "预算从五位数砍到个位数", "en": "Five digits down to one" }] },{ "start": 10, "action": "idle", "from": 1.3, "to": 1.0,"badge": { "text": "60FPS / $0", "t": 1.2 },"lines": [{ "cn": "画面全代码,渲染零云成本", "en": "All code, zero cloud rendering" }] }]}
The “floater” added in act 2 and the “badge” added in act 3 changed only two lines of config. The skeleton and action code were untouched, so the character’s rig is naturally unaffected.
The camera function only computes zoom and pan:
// single-act camera: linear zoom change, target point always follows the character's hipfunction zoomAt(act, u, s) {const z = act.from + (act.to - act.from) * u;return { scale: z, cx: s.hip.x, cy: s.hip.y - 60 };}
Whether the camera pushes in or pulls out, the skeleton is solved in world coordinates first and transformed as a whole afterward. The picture can grow or shrink; the character’s proportions never change.
3.5 Subtitles: an independent layer decoupled from the skeleton
Subtitles are shown by timestamp lookup and do not depend on pose computation. The two-line layout puts Chinese on top and English below, and the English line can be switched off when space is tight. Subtitles, floaters, and badges all render in an HTML overlay composited in layers with the Canvas image, so editing copy can never touch the skeleton.
4. Practice: Generating a 15-Second, Three-Act Animation
Start a new conversation and describe only the requirement:
Use stickman-animator to build a 15-second, 3-act stickman animation. Act 1: the character walks in, bilingual subtitles “省下一笔外包 / No outsourcing budget”; Act 2: stops and waves, subtitle “预算从五位数砍到个位数 / Five digits down to one”; Act 3: camera pulls back to close, subtitle “画面全代码,渲染零云成本 / All code, zero cloud rendering”. Output 720P, 60fps.
The coding agent recognizes this as a stickman animation task, loads the skill automatically, and generates the page skeleton plus act.json under the constraints. The finished piece is exactly 900 frames, which is 15 seconds times 60fps. Opening the page for a self-check confirms natural transitions between acts, coherent proportions, and synced Chinese and English.
Two visual tweaks followed: a floating “-$” symbol during the wave in act 2, and a “60FPS / $0” badge in the bottom-right corner of act 3. The model appended two config entries in act.json only; the render pipeline was not modified, and the update took about a minute and a half.
5. Local Export: Turning Rerolls Into Deterministic Production
5.1 Frame-by-frame rendering instead of screen recording
The export script launches a browser in headless mode, calls the render function at exact frame / fps timestamps, and hands the frames to a command-line encoder to produce an MP4:
// export-mp4.js (sketch): headless browser + command-line encoder// 1. launch the browser in headless mode and open the finished HTML// 2. total = Math.round(duration * fps) // 15 × 60 = 900// 3. for i = 0 .. total-1:// page.evaluate(t => window.renderFrame(t), i / fps)// frame = page.screenshot({ clip: the frame area })// 4. start the command-line encoder, example arguments:// -framerate 60 -i frames/%04d.png -c:v libx264 -pix_fmt yuv420p// -movflags +faststart out.mp4
Screen recording is not recommended:
- Screen capture can drop frames, so the effective frame rate is not constant.
- The exact timing between consecutive frames cannot be controlled.
Frame-by-frame rendering is essentially programmatic rendering: each frame is determined solely by renderFrame(t), which is controllable and reproducible.
Measured: exporting the full 720P, 60fps, 900-frame piece takes about 52 seconds and produces a file of roughly 0.81 MB. Stickman footage is a “solid background, line-art subject” image with tiny inter-frame differences, so inter-frame compression in the video encoder is very efficient and the bitrate stays low.
Run a self-check before exporting:
- Dropped-frame check: the screenshot buffer length must equal the expected frame count. If the screenshot call is never executed in the loop above (for example, a Promise is written without
await), the buffer is empty and the self-check fails immediately. - Skeleton invariant check: sample a number of frames at random and verify that shoulder-elbow and hip-knee distances equal the bone lengths exactly.
- First/last frame continuity check: the pose in the first and last frames should connect naturally.
5.2 Local rendering does not consume cloud compute
Only model calls incur cost:
- Text output is billed per token, independent of video duration or resolution.
- Video encoding runs locally, so no cloud GPU instance is used and there is no per-second rendering charge.
6. The Math: Deterministic Production vs. Generative Video
| Dimension | Code animation pipeline (skill + local rendering) | Generative video (probabilistic reroll) |
|---|---|---|
| Cost structure | One-time investment in the first piece for building the skill, debugging scripts, and exporting; per-token billing afterward | Billed per piece, per attempt |
| Change one line of dialogue | Edit config and re-export, about one minute | Usually a full regeneration, billed again |
| Character consistency | Bone lengths locked, consistent at any frame and any camera | Independent sampling each time, prone to drift |
| Reproducibility | Identical config renders an identical result | The same prompt twice can produce different results |
| Visual style | Geometric, flat, strong design feel | Photorealistic, rich materials and lighting |
The actual spend for this approach was the cumulative cost of generating v2 of the 15-second, 3-act animation, completing several rounds of revisions, and running export tests: about $0.54. At that pace, 30 pieces cost roughly $16.20 per month.
On unit price alone, the code pipeline is not necessarily cheaper than some generative services. The real dividing line is the cost of change:
- With generative video, changing one line of dialogue means paying to reroll the whole clip. A single copy tweak costs a full regeneration.
- With the code pipeline, changing dialogue means editing two config lines and re-exporting, about one minute. The character’s skeleton never deforms.
That is the difference between deterministic and probabilistic: the former gives predictable input-to-output every time, the latter gives unpredictable results for every input.
7. Boundaries: Who This Does Not Suit
- Photorealistic footage with real materials and lighting: the stickman approach cannot deliver this by nature.
- Teams without a local development environment or unwilling to touch a command line: frame-by-frame export depends on a local runtime, a browser, and a command-line encoder, so it is not a fit for pure no-code users.
- Complex interaction and physics: cloth, fluids, particles, and similar simulations exceed what a joint-angle system can express.
In short: when a shot can be expressed as “geometric shapes plus time functions,” the code pipeline has a clear advantage; when a shot depends on the complex physics of the real world, it falls short.
8. Recommendations for Getting Started
Teams stuck in the “generate, dislike, regenerate” loop can start from a minimal skill:
- Write constraints before code: put non-negotiable hard constraints in the instruction file so every model output is bound by them.
- Separate parameters from code: keep frame dimensions, bone lengths, actions, and subtitles in separate files, so copy edits and pacing edits never interfere.
- Solidify verifiable invariants: constant bone lengths, first/last frame continuity, frame count equal to duration times frame rate, so “is it correct” can be decided by a program rather than by eyeballing samples.
- Establish reproducibility before optimizing speed: frame-by-frame rendering is slightly slower than screen recording, and in exchange any change can reproduce exactly the same result.
Only when animation stops being a reroll and becomes a build does content production gain the predictable, accumulable engineering properties it needs.
