簡體   English   中英

在Svg中獲取String的像素長度

[英]Get pixel length of String in Svg

我目前正在使用SVG。 我需要知道字符串長度(以像素為單位)才能進行一些對齊。 如何獲取像素的字符串長度?

更新:感謝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>

我一直在想這個,我很高興地發現,根據SVG規范,有一個特定的函數來返回這個信息: 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/

在閱讀了各種類似的線程並感興趣並從一些想法中受益之后,我創建了一個頁面,它將三種Javascript方法並排比較。 我已經注意到了結果

IE9

Firefox 29.0.1和

Chrome 34.0.1847.131 m

您可以在瀏覽器中加載它,看看哪些適合您:

http://bl.ocks.org/MSCAU/58bba77cdcae42fc2f44

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM