How to get width of tspan SVG element

I am trying to get the rendered width of the tspan element (located inside the text element) in SVG.

This is my markup:

 <text> <tspan>Value 1</tspan> <tspan>Value 2</tspan> </text> 

Visually, I want a value of 1 to float to the left, and a value of 2 floats to the right, so that multiple elements will align as such:

 Value 1 Value 2 Value 10 Value 20 Value 100 Value 200 Value 1000 Value 2000 

Since I want the width of tpsan ("value 1" / "value 2") and not a text element, I cannot use getBBox() since this method does not apply to tspan elements.

Oddly enough, using the jQuery width() method will return the correct value in Chrome, but will return NaN in Firefox. Any ideas would be appreciated.

+6
javascript jquery svg
source share
2 answers

You can use getBoundingClientRect() to find the bounding rectangle of the tspan screen. I tested and found that this works in Safari v5.0.4, Firefox 3.6 and 4.0RC and Opera 11. However, it does not work with Chrome , v10.0.648.151 and v11.0.696.14. (It returns a ClientRect with all values ​​set to 0 )

You will have to convert this client space rectangle to SVG coordinates, multiplying it by the inverse of the screen transformation matrix. Here is a working example:
http://phrogz.net/SVG/tspan_bounding_box.xhtml

Compare this to offsetWidth (which works in Chrome and Safari, but not in Firefox or Opera), and you have a solution that should work in all browsers that support SVG.

+3
source share

After several attempts, I found getComputedTextLength the most accurate way to get the svg tspan width. It is also well supported and behaves the same in different browsers. I also found that the best way to get the tspan height is to simply read the font-size attribute.

+7
source share

All Articles