svg附加文本元素-给我错误的宽度 [英] svg appending text element - gives me wrong width
问题描述
我正在通过JavaScript将文本元素附加到svg.但是,在添加了我要设置的x和y坐标后,使用它计算x时会返回错误的文本元素宽度.
i'm appending a text element to a svg via javascript. After appending i wanna set x and y coordinate, however, it returns me the wrong width of the text element when using it to calculate x.
有趣的是: 在Chrome浏览器中,通过F5或按钮实现页面宽度错误时,在地址栏中按Enter时,宽度正确-很奇怪!
Interesting: In Chrome, when actualize the page via F5 or button it returns wrong width, when pressing enter in the adress bar, the width is right - strange!
这是小代码:
var capt = document.createElementNS("http://www.w3.org/2000/svg", "text");
// Set any attributes as desired
capt.setAttribute("id","capt");
capt.setAttribute("font-family","Righteous");
capt.setAttribute("font-size","30px");
capt.setAttribute("fill", "rgb(19,128,183)");
var myText = document.createTextNode(this.options.captTxt);
capt.appendChild(myText);
this.elements.jSvgElem.append(capt);
capt.setAttribute("x", this.options.windowWidth-this.options.spacer-document.getElementById("capt").offsetWidth);
capt.setAttribute("y", this.options.captY+$('#capt').height());
推荐答案
好的,问题似乎是浏览器在使用其他字体时无法计算正确的宽度.不设置字体会导致正确的宽度.
OK, the problem seems to be that the browser doesn't calculate the correct width when using an other font. Not setting a font results in a correct width.
我通过设置属性将参考点(对齐点")设置到文本元素的右上角来解决了这个问题:
I solved the problem by setting the reference point ("alignment-point") to the upper right corner ot the text element by setting attributes:
capt.setAttribute("text-anchor","end"); capt.setAttribute("alignment-baseline","hanging");
capt.setAttribute("text-anchor", "end"); capt.setAttribute("alignment-baseline", "hanging");
这样,我不必减去元素的宽度并增加其高度!
This way i do not have to subtract the width and add the height of the element!
这篇关于svg附加文本元素-给我错误的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!