I have SVG elements that must be processed inside a JSDOM and need to obtain their getBBox() value.
while using getBBox() , as there is not painting performed inside a JSDOM the values are not obtained.
As I have many svgs in files and am in need of a method that finds the x, y , min ,max coordinates as like getBBox() and return those values. I have also tried methods like getBoundingClientRect()
https://github.com/jsdom/jsdom/issues/2647 If getBBox() can't be used inside a JSDOM , is there any alternative approach for the same.
You can't replicate
getBBox()in a headless environment without emulating a full fledged CSS and SVG rendering engine.Calculate BBox from x/y extremes
Provided, your svgs only contain geometry elements you can actually calculate a bounding box from the element's extreme x/y coordinates.
Illustration from w3c §8.10. Bounding boxes
The geometry element class includes:
<path>,<polygon>,<polyline>,<circle>,<ellipse>,<rect>,<line>elements.Obviously, things get a bit more complicated with
<path>elements as we first need to parse and normalize the path data to computable data objects.For instance we need to convert relative commands to absolute. Besides, we need all segments to use longhand commands (e.g.
t=>Q,s=>C,h/v=>L). See also "Get bounding box of SVG path".getBBox in node.js/jsDom
You'll find quite a few libraries on npm. See search result for "svg bounding box".
The above example is based on my own experimental library/repository you can install via npm like so
Combined with jsDom you can get a bbox like so
Limitations/not supported
1.
<text>elementsCalculating a bbox for a text element would require to retrieve and parse the used font family (already not trivial as this font needs to be available for loading ... or you need a routine to auto detect paths, external URLS etc.).
Then you would need to calculate the total boundaries e.g. by converting text to path and computing all characters bboxes. See related SO post "D3js : How to convert svg text to path?"
Quite likely you won't be able to approximate all kind of text objects (text paths, texts using variable or color fonts)
2. elements styled by CSS
As we can also define a lot of "presentation attributes" via CSS e.g
d(path data) we would ultimately need a full fledged CSS parser to calculate the bounding box coming from CSS rules. Not aware of a node library that is capable of this :(3. Transformed elements
Transformations are ignored. You may convert all transformations to hardcoded coordinates.