Get pixel length of String in Svg

后端 未结 2 406
太阳男子
太阳男子 2020-12-25 11:28

I\'m currently working with SVG. I need to know the string length in pixels in order to do some alignment. How can I do to get the length of a string in pixel ?

相关标签:
2条回答
  • 2020-12-25 12:21

    I've been wondering this too, and I was pleasantly surprised to find that, according to the SVG spec, there is a specific function to return this info: getComputedTextLength()

    // access the text element you want to measure
    var el = document.getElementsByTagName('text')[3];
    el.getComputedTextLength(); // returns a pixel integer
    

    Working fiddle (only tested in Chrome): http://jsfiddle.net/jyams/

    0 讨论(0)
  • 2020-12-25 12:30

    Having read various similar threads with interest and benefitted from some of the ideas, I've created a page which compares three of the Javascript methods side-by-side. I've noted results in

    IE9

    Firefox 29.0.1 and

    Chrome 34.0.1847.131 m

    You can load it in your browser and see what works for you:

    http://bl.ocks.org/MSCAU/58bba77cdcae42fc2f44.

    0 讨论(0)
提交回复
热议问题