svgdom
svgdom copied to clipboard
Text `bbox` is empty when using font-size with units
It seems that when <text>
or <tspan>
elements have a font-size which includes a unit, this library renders their .bbox()
as an empty rect (all 0's). The following example illustrates my point.
const {SVG, registerWindow} = require("@svgdotjs/svg.js")
const {createSVGWindow} = require("svgdom")
const window = createSVGWindow()
registerWindow(window, window.document)
const svg = SVG().svg(`
<text id="unitless" font-size="20">Test</text>
<text id="px" font-size="20px">Test</text>
`)
console.log("unitless:", svg.findOne("#unitless").bbox())
console.log("px:", svg.findOne("#px").bbox())
Which outputs the following when run in node:
unitless: Box {
x: 0,
y: -21.376953125,
w: 38.88671875,
width: 38.88671875,
h: 27.236328125,
height: 27.236328125,
x2: 38.88671875,
y2: 5.859375,
cx: 19.443359375,
cy: -7.7587890625
}
px: Box {
x: 0,
y: 0,
w: 0,
width: 0,
h: 0,
height: 0,
x2: 0,
y2: 0,
cx: 0,
cy: 0
}
Units are rarely used in svg. whats your usecase?
I'm importing and manipulating preexisting SVGs that happen to use units for their font-sizes.
A small step in the right direction might be to at least warn or document somewhere that measurements with units aren't supported or something. It took me a while to figure out why my text fields just weren't measuring at all.
Or we could just skip the unit alltogether. Feel free to implement a PR. You should find the corresponding code somewhere in https://github.com/svgdotjs/svgdom/blob/master/src/utils/textUtils.js
I think ignoring the unit would work for the case of px
, but other units mean different things than the scalar values represent. I'll see if I can get a coherent PR together on this. Thanks for pointing me in the right direction in the codebase.
This library has no notion of real-world measurements. How much is a cm in px if you don't have a screen? There is no way to know. The only other unit that would make sense is percentage but in the end, this is a custom library that supports as much as it can. What works works and when somebody needs more, they can create a PR :)