JSPM

@svg-fns/layout

0.1.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 118
  • Score
    100M100P100Q75728F
  • License MPL-2.0

Lightweight SVG layout utilities — viewBox parsing, scaling, cropping, and trimming for precise content-aware rendering.

Package Exports

  • @svg-fns/layout

Readme

@svg-fns/layout

test codecov Version Downloads npm bundle size NPM License

Utilities for SVG layout manipulation — parse, scale, crop, and trim <svg> viewBoxes with precision.
Part of the svg-fns ecosystem.


✨ Features

  • 🔍 Parse & inspect SVG viewBox values
  • ✂️ 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/layout

or

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 box
  • mutate: boolean = true — apply changes directly to <svg> (set to false for 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