gpt4 book ai didi

javascript - 获取 Svg 中字符串的像素长度

转载 作者:行者123 更新时间:2023-12-03 00:22:30 26 4
gpt4 key购买 nike

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

工作 fiddle (仅在 Chrome 中测试):http://jsfiddle.net/jyams/

关于javascript - 获取 Svg 中字符串的像素长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10254644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com