Calculating vertical height of a SVG text
14,603
You can use getBBox
method to calculate dimensions of the SVG nodes.
var textNode = document.getElementsByTagName('text'),
bbox = textNode.getBBox();
//bbox now have x, y, width and height properties
Author by
Scaraffe
Updated on July 18, 2022Comments
-
Scaraffe almost 2 years
I have an array of strings. Say,
['Jan 11','Feb 11']
And i am creating a vertical text with these string like so
<text x="60" y="154" text-anchor="middle" style="text-anchor: middle; font: normal normal normal 12px/normal Helvetica, Arial; " font="12px Helvetica, Arial" stroke="none" fill="#ffffff" transform="rotate(90 59.75 150)"> <tspan>Jan 11</tspan> </text>
After the svg has been rendered i find that the height of the text is 36px. Now is there a way to calculate the height of a text that will be rendered beforehand given the font-size?
-
Scaraffe over 12 yearsYeah. But that is after the node has been rendered. I was looking for a way to calculate height before render using only the array string.
-
Erik Dahlström over 12 yearsYou can append the node with
visibility="hidden"
specified, then call getBBox, and then unhide it when you've made whatever tweaks you needed. Since svg doesn't use the CSS box model it doesn't affect the layout of other svg elements. It's good to do it like that because some properties on the text element may depend on the context (parent elements, cascaded styles etc). -
sym3tri about 11 yearsCalling getBBox() on hidden nodes with throw an exception in Firefox
-
Tyler Rick over 10 yearsI noticed that they set the "opacity" to 0 in this example rather than using visibility. Perhaps to work around problems with Firefox?
-
Brian Jordan about 9 yearsWorth noting calling
getBBox
on text nodes returns inaccurate measurements in IE10 and IE11 connect.microsoft.com/IE/feedback/details/791152/… -
Lazar Ljubenović about 4 yearsThese dimensions and position are relative to the page, not the SVG space. I'm baffled by presence of .getTextLength() but no .getTextHeight() or similar.