我目前正在使用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 ?
更新:感谢nrabinowitz。基于他的帮助,我现在可以获得动态添加文本的长度。这是一个例子:
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="www.w3/2000/svg" xmlns:xlink="www.w3/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 = "www.w3/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>推荐答案
我一直在想这个,我当时令人惊喜地发现,根据SVG规范,有一个特定的功能可以返回此信息: getComputedTextLength( )
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工作小提琴(仅在Chrome中测试): jsfiddle/jyams/
Working fiddle (only tested in Chrome): jsfiddle/jyams/
更多推荐
在Svg中获取String的像素长度
发布评论