Package Exports
- @svg-fns/layout
Readme
@svg-fns/layout 
Utilities for SVG layout manipulation — parse, scale, crop, and trim <svg> viewBoxes with precision.
Part of the svg-fns ecosystem.
✨ Features
- 🔍 Parse & inspect SVG
viewBoxvalues - ✂️ Crop tightly to visible content (
tightlyCropSvg) - 📐 Scale & zoom around any anchor point
- 📦 Works in browser + Node.js (JSDOM)
- ⚡ Zero dependencies, tree-shakeable
📦 Install
pnpm add @svg-fns/layoutor
npm install @svg-fns/layout🚀 Usage
import {
getViewBox,
setViewBox,
scaleViewBox,
tightlyCropSvg,
computeTrimBox,
} from "@svg-fns/layout";
// Example: crop an SVG tightly to its contents
const svg = document.querySelector("svg")!;
const { box } = tightlyCropSvg(svg, { padding: 2, mutate: true });
// Example: zoom into center by 2x
scaleViewBox(svg, 2, undefined, undefined, { mutate: true });
// Example: read current viewBox
const vb = getViewBox(svg);
console.log(vb); // { x, y, width, height }📚 API
getViewBox(svg: SVGSVGElement): Rect | null
Get the viewBox of an <svg> as { x, y, width, height }.
setViewBox(svg: SVGSVGElement, box: Rect): void
Update the viewBox.
computeTrimBox(svg: SVGSVGElement): Rect
Compute a tight bounding box of the SVG contents.
tightlyCropSvg(svg: SVGSVGElement, opts?): { box: Rect }
Crop an SVG tightly to its contents, with optional padding.
padding: number = 0— extra space around the trim boxmutate: boolean = true— apply changes directly to<svg>(set tofalsefor pure calculation)
scaleViewBox(svg: SVGSVGElement, factor: number, cx?, cy?, opts?): Rect
Scale the current viewBox around an anchor (default: center).
🧪 Testing
pnpm test🙏 Acknowledgments
Thanks to the SVG spec authors and OSS community for foundational ideas. Part of svg-fns — modular, functional SVG utilities.
License
This library is licensed under the MPL-2.0 open-source license.
Please enroll in our courses or sponsor our work.
with 💖 by Mayank Kumar Chaudhari