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

标签 javascript svg ecmascript-6

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

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/

相关文章:

javascript - js 注入(inject)扰乱了我所有的代码

javascript - jquery ajax 添加到mysql数据库

html - svg 背景的垂直重复间隙

javascript - 递归复制而不覆盖

javascript - 扩展原型(prototype)、继承和 super

Javascript 树搜索算法,返回包含找到的术语及其父项的树的子集

javascript - 一步一步的 Angular JS 验证不起作用

javascript - 单击主体上的任意位置并调用函数

SVG 文本质量差?

javascript - 如何使用旋转值使用变换或数学来旋转 SVG 矩形?