在SVG中进行Ajax更新会破坏getBBox,有没有解决方法?

mtr*_*ven 8 ajax firefox svg bounding-box

我有一个带有一些复杂图表的SVG页面; 我正在尝试添加通过Ajax调用按需插入更多复杂性的代码.这主要是有效的,但插入的节点行为不正常.特别是getBBox()在某些元素上失败,在Firefox中,错误是这样的:

uncaught exception: [Exception... "Component returned failure code: 0x80004005  (NS_ERROR_FAILURE) [nsIDOMSVGLocatable.getBBox]"  nsresult: "0x80004005 (NS_ERROR_FAILURE)"  location: "JS frame :: http://localhost:1555/svg-scripts.js :: addBackground :: line 91"  data: no]
Run Code Online (Sandbox Code Playgroud)

问题似乎与这个问题有关:https: //bugzilla.mozilla.org/show_bug.cgi?format = manyple&id = 612118 但在我的情况下,对象肯定是渲染的,我可以看到它们.

任何见解或变通方法都表示赞赏.不幸的是,我不能轻易指出一个例子,因为这依赖于服务器交互.

gav*_*koa 8

请参阅https://bugzilla.mozilla.org/show_bug.cgi?id=612118 ( SVGLocatable.getBBox()失败,除非附加并呈现它所应用的SVG元素).

您必须将元素放到SVG中,style.display必须是非"none".

另请参见jQueryUI选项卡中的SVG'getBBox'失败

我通过将文本放在不可见区域([-1000; -1000])来解决问题:

function SVGlibText(x, y, text) {
    this.value = document.createElementNS(SVGlibBase.svgNS, "text");
    this.value.setAttribute("x", x);
    this.value.setAttribute("y", y);
    this.value.textContent = text;
}
SVGlibText.prototype.moveTo = function(x, y) {
    this.value.setAttribute("x", x);
    this.value.setAttribute("y", y);
    return this;
}
SVGlibText.prototype.getW = function() {
    return this.value.getBBox().width;
}
SVGlibText.prototype.getH = function() {
    return this.value.getBBox().height;
}

var text = new SVGlibText(-1000, -1000, "Hello world!");
Run Code Online (Sandbox Code Playgroud)

获得宽度/高度:

var textW = text.getW();
var textH = text.getH();
Run Code Online (Sandbox Code Playgroud)

并在计算后使用宽度/高度(需要宽度/高度以确定文本的位置)将文本放置到必要的位置:

text.moveTo(off, off + textH);
Run Code Online (Sandbox Code Playgroud)

  • 对我来说关键是svg元素不能没有style.display. (2认同)