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
Share:
14,603
Scaraffe
Author by

Scaraffe

Updated on July 18, 2022

Comments

  • Scaraffe
    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
    Scaraffe over 12 years
    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.
  • Erik Dahlström
    Erik Dahlström over 12 years
    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).
  • sym3tri
    sym3tri about 11 years
    Calling getBBox() on hidden nodes with throw an exception in Firefox
  • Tyler Rick
    Tyler Rick over 10 years
    I noticed that they set the "opacity" to 0 in this example rather than using visibility. Perhaps to work around problems with Firefox?
  • Brian Jordan
    Brian Jordan about 9 years
    Worth noting calling getBBox on text nodes returns inaccurate measurements in IE10 and IE11 connect.microsoft.com/IE/feedback/details/791152/…
  • Lazar Ljubenović
    Lazar Ljubenović about 4 years
    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.