Designing Vector‑Based Character Rigs for Bone‑Tool Animation

Intermediate  Dec 5, 2026

Learn how to build a reusable bone‑tool rig for 2D vector characters, export it with PHP, and animate it smoothly with JavaScript.

Designing Vector‑Based Character Rigs for Bone‑Tool Animation

# Designing Vector‑Based Character Rigs for Bone‑Tool Animation

Designing a bone‑tool rig for a 2D vector character lets you animate complex motions without drawing each frame. This tutorial walks you through the entire workflow, from vector preparation to a secure PHP backend that stores rig data, and finishes with a lightweight JavaScript engine that drives the animation.

The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Understanding the Bone‑Tool Workflow

The bone‑tool approach mimics a skeletal system: each bone controls a group of vector shapes, and hierarchical relationships let child bones inherit rotation, scale, and translation from their parents. The main benefits are:
- Reusability – the same rig can drive multiple characters.
- Consistency – motion curves stay uniform across scenes.
- Efficiency – only the bone parameters change, not the vector art itself.

The workflow consists of four stages:
1. Create clean vector parts.
2. Define a bone hierarchy.
3. Bind parts to bones (weight painting).
4. Export the rig for runtime playback.

The main points of this section.
The main points of this section.

Preparing Vector Assets

Start with a vector editor that supports grouping and naming (e.g., Adobe Animate, Synfig, or an open‑source SVG tool). Keep these rules in mind:
- Each movable limb or segment should be a separate layer or group.
- Anchor points must be placed at natural rotation pivots (e.g., elbow joint at the elbow).
- Use consistent naming conventions like arm_left, forearm_left, hand_left.

Export the artwork as an SVG file; the XML structure preserves group names, which we will parse later. A minimal example:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <g id="torso">
    <rect width="60" height="120" x="70" y="40" fill="#8bc34a"/>
  </g>
  <g id="upper_arm_left" transform="rotate(0 70 80)">
    <rect width="20" height="60" x="60" y="80" fill="#ff9800"/>
  </g>
  <!-- more groups ... -->
</svg>

When you load this SVG in the browser, each <g> element becomes a manipulable DOM node.

The main points of this section.
The main points of this section.

Building the Bone Hierarchy

A bone is a simple JavaScript object with three properties: name, parent, and transform. The transform holds x, y, rotation, scaleX, scaleY. Create the hierarchy in a JSON file that mirrors the visual structure:

[
  {"name":"root","parent":null,"transform":{"x":100,"y":100,"rotation":0,"scaleX":1,"scaleY":1}},
  {"name":"torso","parent":"root","transform":{"x":0,"y":0,"rotation":0,"scaleX":1,"scaleY":1}},
  {"name":"upper_arm_left","parent":"torso","transform":{"x":-30,"y":-20,"rotation":0,"scaleX":1,"scaleY":1}},
  {"name":"forearm_left","parent":"upper_arm_left","transform":{"x":0,"y":-50,"rotation":0,"scaleX":1,"scaleY":1}}
]

Notice how each bone’s local coordinates are defined relative to its parent. This makes it easy to compute world matrices by walking up the chain.

Building the Bone Hierarchy
Building the Bone Hierarchy

Weight Painting and Constraints

Weight painting tells the engine how much each vector group follows a bone. In a pure 2D rig you usually assign a group to a single bone (100 % weight). For more advanced deformations you can blend two bones, but that requires a shader‑like approach and is beyond this tutorial.

To bind a group to a bone, add a data-bone attribute to the SVG element:

<g id="upper_arm_left" data-bone="upper_arm_left">
  <rect width="20" height="60" x="60" y="80" fill="#ff9800"/>
</g>

> Note: SVG does not have a CSS transform-origin property. The pivot is defined by the transform attribute (e.g., rotate(angle cx cy)) that you set in the editor before exporting.

During runtime the JavaScript engine will read this attribute, locate the matching bone, and apply the bone’s world matrix to the group’s transform attribute.

How the code in this section fits into the page.
How the code in this section fits into the page.

Securely Storing the Rig with PHP and MySQL

A typical web‑based authoring tool lets designers upload an SVG and a JSON rig file. The backend must validate, sanitize, and store the data using prepared statements to avoid SQL injection. Below is a minimal but safer PHP 8 script.

<?php
declare(strict_types=1);
// config.php – keep credentials out of the web root
require_once __DIR__.'/config.php';

session_start(); // required for CSRF token handling

// ---------------------------------------------------------------------
// CSRF protection – generate token elsewhere and store in the session.
// ---------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST' ||
    !hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    http_response_code(403);
    exit('Invalid request');
}

// ---------------------------------------------------------------------
// Validate uploaded files (size, MIME type, basic sanity checks)
// ---------------------------------------------------------------------
$maxSize = 2 * 1024 * 1024; // 2 MiB
$svg  = $_FILES['svg'] ?? null;
$json = $_FILES['rig'] ?? null;

if (!$svg || $svg['error'] !== UPLOAD_ERR_OK ||
    !$json || $json['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    exit('File upload failed');
}

if ($svg['size'] > $maxSize || $json['size'] > $maxSize) {
    http_response_code(413);
    exit('Uploaded file is too large');
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
if ($finfo->file($svg['tmp_name']) !== 'image/svg+xml') {
    http_response_code(400);
    exit('SVG file must be of type image/svg+xml');
}
if ($finfo->file($json['tmp_name']) !== 'application/json') {
    http_response_code(400);
    exit('Rig file must be JSON');
}

$svgContent  = file_get_contents($svg['tmp_name']);
$rigContent  = file_get_contents($json['tmp_name']);

// ---------------------------------------------------------------------
// Basic sanity checks – ensure SVG starts with <svg and JSON is decodeable
// ---------------------------------------------------------------------
if (stripos($svgContent, '<svg') === false) {
    http_response_code(400);
    exit('Invalid SVG file');
}

$rigData = json_decode($rigContent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    exit('Invalid JSON rig file');
}

// ---------------------------------------------------------------------
// SVG sanitisation – strip <script> tags and disable external entities
// ---------------------------------------------------------------------
$dom = new DOMDocument();
$dom->loadXML($svgContent, LIBXML_NOENT | LIBXML_DTDLOAD | LIBXML_NOERROR);
// Remove any <script> elements
$scripts = $dom->getElementsByTagName('script');
while ($scripts->length) {
    $scripts->item(0)->parentNode->removeChild($scripts->item(0));
}
$sanitizedSvg = $dom->saveXML();

// ---------------------------------------------------------------------
// Store in MySQL using prepared statements (UTF‑8 safe)
// ---------------------------------------------------------------------
$pdo = new PDO($dsn.';charset=utf8mb4', $dbUser, $dbPass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
]);
$sql = "INSERT INTO character_rigs (name, svg_data, rig_json, created_at) VALUES (:name, :svg, :rig, NOW())";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':name' => $_POST['character_name'] ?? 'Unnamed',
    ':svg'  => $sanitizedSvg,
    ':rig'  => json_encode($rigData, JSON_UNESCAPED_UNICODE)
]);

echo 'Rig saved successfully';
?>

The accompanying SQL creates a safe container for the data:

CREATE TABLE character_rigs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    svg_data MEDIUMTEXT NOT NULL,
    rig_json JSON NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX (name)
) ENGINE=InnoDB;

All text is stored as UTF‑8, and the JSON column lets MySQL validate the structure automatically.

> Security tip: Serve the SVG with an appropriate Content‑Security‑Policy header (e.g., default-src 'none'; img-src data:; style-src 'self';) to mitigate any remaining XSS risk.

The table described by the SQL above.
The table described by the SQL above.
How the code in this section fits into the page.
How the code in this section fits into the page.

Driving the Animation with JavaScript

At runtime we load the SVG inline, parse the rig JSON, and start an animation loop. The core of the engine is a recursive function that builds a world matrix for each bone.

// utils.js – matrix helpers (column‑major 3×3 for 2D)
function mulM(a, b) {
  // column‑major multiplication (a * b)
  return [
    a[0]*b[0] + a[1]*b[3] + a[2]*b[6],
    a[0]*b[1] + a[1]*b[4] + a[2]*b[7],
    a[0]*b[2] + a[1]*b[5] + a[2]*b[8],
    a[3]*b[0] + a[4]*b[3] + a[5]*b[6],
    a[3]*b[1] + a[4]*b[4] + a[5]*b[7],
    a[3]*b[2] + a[4]*b[5] + a[5]*b[8],
    a[6]*b[0] + a[7]*b[3] + a[8]*b[6],
    a[6]*b[1] + a[7]*b[4] + a[8]*b[7],
    a[6]*b[2] + a[7]*b[5] + a[8]*b[8]
  ];
}
function compose(t) {
  const rad = t.rotation * Math.PI/180;
  const cos = Math.cos(rad), sin = Math.sin(rad);
  // column‑major 3×3 matrix
  return [
    cos*t.scaleX, -sin*t.scaleY, t.x,
    sin*t.scaleX,  cos*t.scaleY, t.y,
    0,            0,            1
  ];
}

// main.js – load SVG and rig, then animate
async function init() {
  const [svgResp, rigResp] = await Promise.all([
    fetch('character.svg'),
    fetch('character_rig.json')
  ]);
  const svgText = await svgResp.text();
  const rig = await rigResp.json();

  const container = document.getElementById('stage');
  container.innerHTML = svgText; // inline SVG

  const bones = {};
  rig.forEach(b => bones[b.name] = {...b, world: null});

  function updateWorld(bone) {
    const local = compose(bone.transform);
    if (bone.parent) {
      const parentWorld = bones[bone.parent].world || updateWorld(bones[bone.parent]);
      bone.world = mulM(parentWorld, local);
    } else {
      bone.world = local;
    }
    return bone.world;
  }

  function applyTransforms() {
    for (const name in bones) {
      const bone = bones[name];
      updateWorld(bone);
      const group = document.querySelector(`[data-bone="${name}"]`);
      if (group) {
        const m = bone.world;
        // SVG `matrix(a,b,c,d,e,f)` expects a,b,c,d,e,f in row‑major order.
        // Our matrix is column‑major, so we map accordingly:
        group.setAttribute('transform', `matrix(${m[0]},${m[3]},${m[1]},${m[4]},${m[2]},${m[5]})`);
      }
    }
  }

  // Simple keyframe animation – swing left arm
  let angle = 0;
  function animate(time) {
    angle = 30 * Math.sin(time/500);
    bones['upper_arm_left'].transform.rotation = angle;
    bones['forearm_left'].transform.rotation = angle/2;
    applyTransforms();
    requestAnimationFrame(animate);
  }
  requestAnimationFrame(animate);
}

init();

The engine does three things:
1. Builds a world matrix per bone.
2. Writes the matrix into the SVG group's transform attribute.
3. Updates the rotation values each frame.
Because the math runs in pure JavaScript, the animation stays smooth on modern browsers without any external libraries.

Driving the Animation with JavaScript
Driving the Animation with JavaScript

Common Mistakes and How to Avoid Them

  • Misplaced pivot points – If the SVG group’s origin does not match the intended joint, the bone will swing around the wrong spot. Set the rotation centre with the rotate(angle cx cy) transform in your editor before exporting.
  • Circular bone references – A bone cannot be its own ancestor. Validate the hierarchy server‑side (e.g., a simple depth‑first search) before saving.
  • Large SVG payloads – Embedding high‑resolution raster images defeats the purpose of vector rigs. Keep the SVG lightweight; use <symbol> elements for reusable parts.
  • Missing CSRF protection – The PHP example includes a token check; remember to generate and store the token in the session when rendering the upload form.
  • Improper data types – Store numeric values as numbers, not strings, in the JSON rig. MySQL’s JSON column will reject malformed numbers.

Final Checklist

  • [ ] Vector groups are clean, named, and have correct anchor points.
  • [ ] Bone hierarchy is acyclic and each bone has a unique name.
  • [ ] Every group that should move has a data-bone attribute matching a bone name.
  • [ ] SVG and rig JSON pass basic validation before upload.
  • [ ] PHP endpoint uses prepared statements, validates CSRF, sanitises SVG, and stores data in a JSON column.
  • [ ] JavaScript matrix helpers are tested with simple rotations.
  • [ ] Animation loop runs at 60 fps on target browsers.
  • [ ] All user‑generated content is served with a strict Content‑Security‑Policy header.

By following these steps you can create a reusable, secure, and performant bone‑tool rig for any 2D vector character, dramatically reducing the time spent on frame‑by‑frame drawing while keeping the workflow fully under your control.

More tutorials