Javascript 获取 Svg 中字符串的像素长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10254644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get pixel length of String in Svg
提问by nxhoaf
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 ?
我目前正在使用 SVG。我需要知道以像素为单位的字符串长度才能进行一些对齐。如何以像素为单位获取字符串的长度?
Update:Thanks to nrabinowitz. Based on his help, I can now get the length of dynamic-added text. Here is an example:
更新:感谢 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>
回答by nrabinowitz
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/
回答by MSC
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
在饶有兴趣地阅读了各种类似的主题并从其中的一些想法中受益后,我创建了一个页面,其中并排比较了三种 Javascript 方法。我已经注意到结果
IE9
IE9
Firefox 29.0.1 and
火狐 29.0.1 和
Chrome 34.0.1847.131 m
铬 34.0.1847.131 m
You can load it in your browser and see what works for you:
您可以在浏览器中加载它,看看哪些对您有用: