在Svg中获取String的像素长度

nxh*_*oaf 27 javascript svg image

我目前正在使用SVG.我需要知道字符串长度(以像素为单位)才能进行一些对齐.如何获取像素的字符串长度?

更新:感谢nrabinowitz.基于他的帮助,我现在可以获得动态添加文本的长度.这是一个例子:

<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>
Run Code Online (Sandbox Code Playgroud)

nra*_*itz 35

我一直在想这个,我很高兴地发现,根据SVG规范,有一个特定的函数来返回这个信息:getComputedTextLength()

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

工作小提琴(仅在Chrome中测试):http://jsfiddle.net/jyams/


MSC*_*MSC 5

饶有兴趣地阅读了各种类似的主题并从中受益之后,我创建了一个页面,将三个Javascript方法并排进行比较。我注意到了

IE9

Firefox 29.0.1和

铬34.0.1847.131 m

您可以在浏览器中加载它,然后查看适合您的方法:

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