38
rated 0 times
[
42]
[
4]
/ answers: 1 / hits: 25434
/ 12 Years ago, fri, april 20, 2012, 12:00:00
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>
More From » image