Introduction
SVG.js provides a clean, readable syntax for creating and manipulating SVG elements in the browser. It covers the full SVG specification — shapes, text, paths, gradients, filters, masks, and patterns — with a chainable API that reads like a sentence. Built-in animation support makes it easy to tween any SVG attribute.
What SVG.js Does
- Creates SVG elements programmatically: rect, circle, ellipse, line, polyline, polygon, path, text, image
- Animates any SVG attribute with built-in easing and timeline support
- Manipulates existing SVG documents by selecting and modifying elements
- Supports gradients, patterns, masks, clip paths, filters, and markers
- Provides event handling, data binding, and CSS class manipulation on SVG elements
Architecture Overview
SVG.js wraps native SVG DOM elements in lightweight proxy objects that expose chainable methods. Each method call modifies the underlying SVG attribute directly. The animation system schedules property changes on a requestAnimationFrame loop with configurable easing. A timeline object orchestrates multiple animations in sequence or parallel. Plugins extend the core by adding methods to the element prototypes.
Self-Hosting & Configuration
- Install via npm or include the ESM/UMD bundle
- Create a drawing surface with
SVG().addTo(container).size(w, h) - Use the plugin system for extensions like svg.filter.js and svg.draggable.js
- Import only needed modules for tree-shaking in bundled applications
- Set viewBox with
.viewbox(x, y, w, h)for responsive SVG sizing
Key Features
- Full SVG spec coverage including filters, gradients, masks, and clip paths
- Chainable API:
draw.circle(50).fill('red').move(10, 10).animate().radius(80) - Built-in animation with timeline, easing, and declarative scheduling
- Plugin ecosystem for draggable, resizable, and filterable elements
- Lightweight core (~16 KB gzipped) with modular imports
Comparison with Similar Tools
- D3.js — data-driven document manipulation with SVG as one output; SVG.js is SVG-focused with a simpler API
- Snap.svg — similar scope but no longer actively maintained; SVG.js has continued releases
- Fabric.js — canvas-based with SVG import/export; SVG.js works directly with the SVG DOM
- Paper.js — vector graphics on canvas; SVG.js renders native SVG elements in the DOM
FAQ
Q: Can SVG.js work with existing SVGs in the DOM?
A: Yes. Use SVG(existingElement) to wrap and manipulate any SVG element already in the document.
Q: How does animation work?
A: Call .animate(duration, ease, delay) on any element, then chain the target state. SVG.js interpolates between current and target values.
Q: Is SVG.js compatible with React? A: Yes. Create the SVG drawing inside a useEffect hook on a container ref. SVG.js manages its own DOM subtree within that container.
Q: Does SVG.js support touch events?
A: Yes. Use .on('touchstart', handler) on any SVG.js element, the same way you bind click or mouse events.