Provides a polyfill for SVG elements in environments where getBBox is not available.
Provides a set of utils to calculate the bounding box of SVG paths and shapes, by using DOMRect, DOMMatrix, DOMPoint and pure math calculations.
As this packges only polyfills getBBox, it still requires other DOM APIs.
Installing happy-dom or jsdom is recommended for non-browser environments.
npm i svg-bbox-polyfill happy-domIt's also very likely you're missing DOMPoint.prototype.matrixTransform (even with happy-dom).
In that case, you can use injectDOMPointPolyfill from this package or any other polyfill.
Inject the polyfill for DOMPoint.prototype.matrixTransform:
import { injectDOMPointPolyfill } from "svg-bbox-polyfill"
injectDOMPointPolyfill(globalThis) // In case `matrixTransform` is missing.Register fonts used in SVGs (required for text elements):
import opentype from "opentype.js"
import { SvgBBox } from "svg-bbox-polyfill"
// Use `opentype.js` or anything that returns `opentype.Font` interface.
SvgBBox.fonts["Arial"] = await opentype.load("path/to/Arial.ttf")
SvgBBox.fonts["Times New Roman"] = opentype.loadSync("path/to/TimesNewRoman.ttf")Compute the bounding box of an SVG element without polyfilling:
import { SvgBBox, injectDOMPointPolyfill } from "svg-bbox-polyfill"
injectDOMPointPolyfill(globalThis) // In case `matrixTransform` is missing. Apply before `SvgBBox.compute`.
SvgBBox.compute(svgElement)
// Other utils:
SvgBBox.computeLine(lineElement)
SvgBBox.computeRect(rectElement)
SvgBBox.computeCircle(circleElement)
SvgBBox.computeEllipse(ellipseElement)
SvgBBox.computePoly(polyElement)
SvgBBox.computeFont(fontElement)
SvgBBox.computeTspan(tspanElement)
SvgBBox.computeTransformedBBox(lineElement)
SvgBBox.computeBoundingBox(rect, transform, origin) // Read inline docs for more details.Inject the polyfill for SVGGraphicsElement (base class for all SVG elements):
import { injectSvgBBoxPolyfill, injectDOMPointPolyfill } from "svg-bbox-polyfill"
injectDOMPointPolyfill(globalThis) // In case `matrixTransform` is missing. Apply before `injectSvgBBoxPolyfill`.
injectSvgBBoxPolyfill(globalThis)
svgElement.getBBox()This polyfill can be used in various scenarios, such as:
- Server-side rendering of SVGs
- Testing SVG-related code in non-browser environments
One of the main use cases of this polyfill is to enable rendering of Mermaid diagrams in server-side environments without tools like Puppeteer or Playwright (@mermaid-js/mermaid-cli is also based on Puppeteer).
Mermaid relies on getBBox to calculate the size and position of SVG elements when rendering diagrams. However, it also relies on other DOM APIs like Canvas, so looks at mermaid-svg-native library.