Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get pixel length of String in Svg

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 ?

Update: Thanks to nrabinowitz. Based on his help, I can now get the length of dynamic-added text. Here is an example:

<svg id="main"      xmlns="http://www.w3.org/2000/svg"      xmlns:xlink="http://www.w3.org/1999/xlink"     version="1.1"      width="1020"     height="620"      viewBox="0 0 1020 620"     onload="startup(evt)">  <script>     <![CDATA[         var startup = function (evt) {             var width;             var svgNS = "http://www.w3.org/2000/svg";             var txtNode = document.createTextNode("Hello");             text = document.createElementNS(svgNS,"text");              text.setAttributeNS(null,"x",100);             text.setAttributeNS(null,"y",100);             text.setAttributeNS(null,"fill","black");             text.appendChild(txtNode);                                                           width = text.getComputedTextLength();                            alert(" Width before appendChild: "+  width);                                    document.getElementById("main").appendChild(text);             width = text.getComputedTextLength();             alert(" Width after appendChild: "+  width)             document.getElementById("main").removeChild(text);                       }            //]]> </script> </svg> 
like image 639
Hoa Nguyen Avatar asked Apr 20 '12 23:04

Hoa Nguyen


People also ask

How do you find the length of a string in pixels?

By their nature, strings do not have lengths in in pixels or something like that. Strings are data structures totally abstracted from the way they are presented, such as fonts, colors, rendering styles, geometrical sizes, etc. Those are all some properties of some UI elements, whatever they are.

How can I get SVG text width?

To get the SVG's text element's width and height with JavaScript, we can call the getBBox method of the text element to get the text's width and height. We get the text element with document. querySelector . Then we call getBBox on the returned textElement to get an object with the dimensions of the text.


1 Answers

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/

like image 141
nrabinowitz Avatar answered Oct 02 '22 16:10

nrabinowitz