在Svg中获取String的像素长度 [英] Get pixel length of String in Svg

查看:313
本文介绍了在Svg中获取String的像素长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用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="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>


推荐答案

我一直在想这个,我当时令人惊喜地发现,根据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中测试): http://jsfiddle.net/jyams/

Working fiddle (only tested in Chrome): http://jsfiddle.net/jyams/

这篇关于在Svg中获取String的像素长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆