Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the width of an SVG tspan element

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

This is my markup:

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

Visually, I want value 1 to float left, while value 2 floats right, so that a 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 the tpsan ("value 1"/"value 2") and not the text element, I can't use getBBox(), as that method doesn't apply to tspan elements.

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

like image 649
RussellUresti Avatar asked Mar 19 '11 21:03

RussellUresti


1 Answers

After trying multiple solutions I found getComputedTextLength to be the most accurate way to get the width of an svg tspan. It is also well supported and behaves the same way on different browsers. I also found that the best way to get the height of a tspan is simply to read the font-size attribute.

like image 90
madmed Avatar answered Sep 21 '22 04:09

madmed