2011-10-13 168 views
9

我有一個字符串數組。再說了,計算SVG文本的垂直高度

['Jan 11','Feb 11'] 

,我創建與這些字符串豎排文本,像這樣

<text x="60" y="154" text-anchor="middle" style="text-anchor: middle; font: normal normal normal 12px/normal Helvetica, Arial; " font="12px Helvetica, Arial" stroke="none" fill="#ffffff" transform="rotate(90 59.75 150)"> 
<tspan>Jan 11</tspan> 
</text> 

後,SVG已經呈現我發現文本的高度爲36px。現在有沒有一種方法可以計算出預先給定字體大小的文本的高度?

回答

14

您可以使用getBBox方法計算SVG節點的尺寸。

var textNode = document.getElementsByTagName('text'), 
    bbox = textNode.getBBox(); 

//bbox now have x, y, width and height properties 
+1

是的。但是,這是節點已被渲染後。我正在尋找一種方法來計算渲染前使用只有數組字符串的高度。 – Scaraffe

+3

你可以在節點上追加'visibility =「hidden」',然後調用getBBox,然後在你做出任何需要的調整時取消隱藏。由於svg不使用CSS盒模型,它不會影響其他svg元素的佈局。這樣做很好,因爲文本元素的一些屬性可能取決於上下文(父元素,級聯樣式等)。 –

+2

在隱藏節點上調用getBBox(),在Firefox中引發異常 – sym3tri