@svg-fns/info
v1.0.0
Published
Lightweight, tree-shakeable utilities to extract structured information (dimensions, aspect ratio, bounding boxes, colors) from SVG elements. Works in both browser and Node.js.
Maintainers
Readme
@svg-fns/info
Lightweight, tree-shakeable utilities to extract structured information from SVGs. Works seamlessly in both browser and Node.js (with DOM shims like JSDOM).
Part of the
svg-fnsecosystem — modular SVG utilities inspired bydate-fns.
✨ Features
- Get dimensions (
width,height) - Compute aspect ratio (
width ÷ height) - Calculate bounding boxes (browser-native or Resvg fallback)
- Extract unique fill and stroke colors
- ⚡ Zero dependencies · Fully tree-shakeable · Runs anywhere
📦 Installation
npm install @svg-fns/infoor
pnpm add @svg-fns/infoor
yarn add @svg-fns/info🚀 Usage
import { getSvgDimensions, getSvgAspectRatio, getSvgBBox, getSvgColors } from "@svg-fns/info";
const svg = document.querySelector("svg")!;
// Dimensions
console.log(getSvgDimensions(svg));
// → { width: 800, height: 600 }
// Aspect ratio
console.log(getSvgAspectRatio(svg));
// → 1.333...
// Bounding box
console.log(getSvgBBox(svg));
// Browser → DOMRect
// Node.js → Promise<DOMRect> (via Resvg or fallback)
// Colors
console.log(getSvgColors(svg));
// → { fills: ["#000", "#f00"], strokes: ["#333"], colors: ["#000", "#f00", "#333"] }📝 Note: These APIs require an
SVGSVGElement. To parse an SVG string, use@svg-fns/io:
import { parseSvg } from "@svg-fns/io";
import { getSvgDimensions } from "@svg-fns/info";
const svgElement = parseSvg("<svg width='100' height='50'/>");
console.log(getSvgDimensions(svgElement));
// → { width: 100, height: 50 }⚡ Performance Notes
Browser: Uses native DOM APIs (
getBBox(),getComputedStyle) → fast and accurate.Node.js:
- With
@resvg/resvg-js→ accurate bounding boxes (Rust-based). - Without Resvg → fallback approximation by traversing child elements.
- With
Aspect ratio: Returns
Infinityifheight = 0(instead ofNaN).
📚 API Reference
getSvgDimensions(svg: SVGSVGElement)
- Returns
{ width, height }. - Uses
width/heightattrs first, then falls back toviewBox.
getSvgAspectRatio(svg: SVGSVGElement)
- Returns
width ÷ height. - Returns
Infinityifheight = 0.
getSvgBBox(svg: SVGSVGElement)
- Browser: Returns
DOMRect(sync). - Node.js: Returns
Promise<DOMRect>(async import of Resvg). - Fallback → approximate bbox traversal.
getSvgColors(svg: SVGSVGElement)
- Returns
{ fills: string[], strokes: string[], colors: string[] }. - Browser → uses computed styles (includes CSS inheritance).
- Node.js → scans element attributes only.
🔗 Related Packages
@svg-fns/io— Parse, serialize, and load SVGs@svg-fns/svg2img— Base64, Blob, rasterization, downloads
🛠️ Contributing
We welcome contributions! 🎉
- Open an issue for bugs/feature requests.
- PRs should include tests + docs.
- See our contributing guide.
📜 License
Licensed under the MPL-2.0 open-source license.
