javascript 计算SVG文本的垂直高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7754734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating vertical height of a SVG text
提问by Scaraffe
I have an array of strings. Say,
我有一个字符串数组。说,
['Jan 11','Feb 11']
And i am creating a vertical text with these string like so
我正在用这些字符串创建一个垂直文本,就像这样
<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>
After the svg has been rendered i find that the height of the text is 36px. Now is there a way to calculate the height of a text that will be rendered beforehand given the font-size?
渲染 svg 后,我发现文本的高度为 36px。现在有没有办法计算将在给定字体大小的情况下预先呈现的文本的高度?
回答by bjornd
You can use getBBox method to calculate dimensions of the SVG nodes.
您可以使用 getBBox 方法计算 SVG 节点的尺寸。
var textNode = document.getElementsByTagName('text'),
bbox = textNode.getBBox();
//bbox now have x, y, width and height properties