svg appending text element - gives me wrong width

China☆狼群 提交于 2020-01-15 04:38:25

问题


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());

回答1:


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!




回答2:


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):

fixBug = function () {
        var text = makeSVG("text", { x: 0, y: 0, fill: "#ffffff", stroke: '#ffffff'});
        text.textContent = "";
        var svg = $("svg")[0];
        svg.appendChild(text);
        var bbox = text.getBBox();
        var Twidth = bbox.width;
        var Theight = bbox.height;
        svg.removeChild(text);

    }

$("svg") - Jquery selector



来源:https://stackoverflow.com/questions/8388625/svg-appending-text-element-gives-me-wrong-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!