简体   繁体   English

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

[英]get width element <text / > (SVG) using js before adding to svg

Good time forum users.好时光论坛用户。 Please tell me how to get the size of the element taking into account the font parameters (size, type, style)请告诉我如何在考虑字体参数(大小、类型、样式)的情况下获取元素的大小

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;

updated Unfortunately, it is not very convenient to change the size after adding, because you have to find all the elements and proportionally change the position.更新不幸的是,添加后更改大小不是很方便,因为您必须找到所有元素并按比例更改位置。 (I initially set up the template engine (handlebars.js) where I pass the necessary parameters and it automatically builds an element with dimensions (the problem is only with get length text). (我最初设置了模板引擎 (handlebars.js),我在其中传递了必要的参数,它会自动构建一个具有维度的元素(问题仅在于获取长度文本)。

在此处输入图片说明

The OP is commenting: OP 正在评论:

I generate an svg object depending on the data received.我根据收到的数据生成一个 svg 对象。 The resulting text can be of different lengths and I need to calculate the size of it to properly generate the object in width.生成的文本可以有不同的长度,我需要计算它的大小以正确生成宽度的对象。

As I've commented: In this case you may begin with whatever size you want for the svg, append the text, get the size of the text, for example using the textLength property, and next you change the size of your svg element正如我所评论的:在这种情况下,您可以从想要的 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>

Assuming that the element has been inserted into the web page, you could use something like this:假设元素已插入到网页中,您可以使用以下内容:

getComputedStyle(tagText).width

However, if you did not specify that width yourself (using CSS, for instance), in your case, the default value will be auto .但是,如果您没有自己指定该宽度(例如,使用 CSS),则在您的情况下,默认值将是auto

If that's the case, you could try to look at the width of the element's parent, doing something like this:如果是这种情况,您可以尝试查看元素父级的宽度,执行如下操作:

tagText.parentElement.offsetWidth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM