简体   繁体   中英

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.

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.

You can use getBoundingClientRect() to find the screen-space bounding box of the tspan . I've tested and found this to work in Safari v5.0.4, Firefox 3.6 and 4.0RC, and Opera 11. However, it fails with Chrome , v10.0.648.151 and v11.0.696.14. (It returns a ClientRect with all values set to 0 .)

You'll have to transform this client-space rectangle into SVG coordinates by multiplying by the inverse of the screen transform matrix. Here's a working example:
http://phrogz.net/SVG/tspan_bounding_box.xhtml

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM