简体   繁体   English

在Svg中获取String的像素长度

[英]Get pixel length of String in Svg

I'm currently working with SVG. 我目前正在使用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. 更新:感谢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>

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() 我一直在想这个,我很高兴地发现,根据SVG规范,有一个特定的函数来返回这个信息: 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/ 工作小提琴(仅在Chrome中测试): http//jsfiddle.net/jyams/

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. 在阅读了各种类似的线程并感兴趣并从一些想法中受益之后,我创建了一个页面,它将三种Javascript方法并排比较。 I've noted results in 我已经注意到了结果

IE9 IE9

Firefox 29.0.1 and Firefox 29.0.1和

Chrome 34.0.1847.131 m 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 . http://bl.ocks.org/MSCAU/58bba77cdcae42fc2f44

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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