gpt4 book ai didi

javascript - 在添加到 svg 之前使用 js 获取宽度元素 (SVG)

转载 作者:行者123 更新时间:2023-11-30 19:40:47 25 4
gpt4 key购买 nike

好时光论坛用户。请告诉我如何在考虑字体参数(大小、类型、样式)的情况下获取元素的大小

let tagText = document.createElementNS("http://www.w3.org/2000/svg", "text");
tagText.setAttributeNS(null, "font-size", 18);
tagText.setAttributeNS(null, "font-weight", 400);
tagText.setAttributeNS(null, "font-family", "Roboto");
tagText.innerHTML = 'Some text ...';
// where ViewPort ??

let widthTitle = tagText.getBBox().width;
console.log('width title: ', widthTitle); // return 0;

已更新不幸的是,添加后改变大小不是很方便,因为你必须找到所有元素并按比例改变位置。 (我最初设置了模板引擎 (handlebars.js),我在其中传递了必要的参数,它会自动构建一个具有尺寸的元素(问题仅在于获取长度文本)。

enter image description here

最佳答案

OP 正在评论:

I generate an svg object depending on the data received. The resulting text can be of different lengths and I need to calculate the size of it to properly generate the object in width.

正如我所评论的:在这种情况下,您可以从 svg 的任何大小开始,附加文本,获取文本的大小,例如使用 textLength 属性,以及接下来你改变你的 svg 元素的大小

let tagText = document.createElementNS("http://www.w3.org/2000/svg", "text");
tagText.setAttributeNS(null, "y", 20);
tagText.textContent = 'Some text ...';
svg.appendChild(tagText)

let widthTitle = tagText.textLength.baseVal.value;

svg.setAttributeNS(null,"viewBox",`0 0 ${widthTitle} 25`)
text{font-size:18px;
font-weight:400;
font-family:Roboto
}
svg{border:1px solid; width:200px;}
<svg id="svg"></svg>

关于javascript - 在添加到 svg 之前使用 js 获取宽度元素 <text/> (SVG),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55422096/

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