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?

Scaraffe
  • 5,041
  • 5
  • 21
  • 20

1 Answers1

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
Yves M.
  • 29,855
  • 23
  • 108
  • 144
bjornd
  • 22,397
  • 4
  • 57
  • 73
  • 3
    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. – Scaraffe Oct 13 '11 at 13:30
  • 3
    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). – Erik Dahlström Oct 15 '11 at 15:01
  • 3
    Calling getBBox() on hidden nodes with throw an exception in Firefox – sym3tri Jun 13 '13 at 18:09
  • I noticed that they set the "opacity" to 0 in [this](https://groups.google.com/forum/#!topic/d3-js/pTVgFuEgCfY) example rather than using visibility. Perhaps to work around problems with Firefox? – Tyler Rick Nov 11 '13 at 22:02
  • 2
    Worth noting calling `getBBox` on text nodes returns inaccurate measurements in IE10 and IE11 https://connect.microsoft.com/IE/feedback/details/791152/svg-getbbox-return-incorrect-value-for-text-elements-in-ie10-serious-bug – Brian Jordan Apr 22 '15 at 20:34
  • 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. – Lazar Ljubenović May 21 '20 at 17:00