Calculating vertical height of a SVG text
Asked Answered
M

1

13

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?

Manchineel answered 13/10, 2011 at 13:19 Comment(0)
A
17

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
Adrell answered 13/10, 2011 at 13:27 Comment(6)
Yeah. 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.Manchineel
You 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).Cummerbund
Calling getBBox() on hidden nodes with throw an exception in FirefoxDisassembly
I noticed that they set the "opacity" to 0 in this example rather than using visibility. Perhaps to work around problems with Firefox?Lyophilize
Worth noting calling getBBox on text nodes returns inaccurate measurements in IE10 and IE11 connect.microsoft.com/IE/feedback/details/791152/…Rajiv
These dimensions and position are relative to the page, not the SVG space. I'm baffled by presence of .getTextLength() but no .getTextHeight() or similar.Cantankerous

© 2022 - 2024 — McMap. All rights reserved.