svg 附加文本元素 - 给我错误的宽度
我正在通过 javascript 将文本元素附加到 svg。但是,在附加后我想设置 x 和 y 坐标,当使用它来计算 x 时,它会返回文本元素的错误宽度。
有趣的: 在 Chrome 中,当通过 F5 或按钮实现页面时,它返回错误的宽度,当在地址栏中按 Enter 时,宽度是正确的 - 奇怪!
这是小代码:
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());
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.
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!
Here is the small code:
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,问题似乎是浏览器在使用其他字体时无法计算正确的宽度。不设置字体会导致正确的宽度。
我通过设置属性将参考点(“对齐点”)设置到文本元素的右上角来解决这个问题:
capt.setAttribute(“text-anchor”, “end”);
capt.setAttribute("对齐基线", "悬挂");
这样我就不必减去元素的宽度并添加元素的高度!
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");
This way i do not have to subtract the width and add the height of the element!
存在错误:http://code.google.com/p/ chromium/issues/detail?id=140472
它只是预先初始化一些计算文本宽度的函数,因此您应该在之前调用此函数(我确信有几行可以删除):
$("svg") - Jquery 选择器
There is a bug:http://code.google.com/p/chromium/issues/detail?id=140472
it just pre init some functions that calculates text width so you should call this function before(i'm sure that there is several extra lines that can be deleted):
$("svg") - Jquery selector