8

我有一个带有一些复杂图表的 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]

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

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

4

2 回答 2

8

请参阅https://bugzilla.mozilla.org/show_bug.cgi?id=612118SVGLocatable.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!");

获取宽度/高度:

var textW = text.getW();
var textH = text.getH();

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

text.moveTo(off, off + textH);
于 2013-01-21T11:40:31.110 回答
0

NS_ERROR_FAILURE错误消息,或

Exception { message: "", result: 2147500037, name: "NS_ERROR_FAILURE", ...}`)

如果您尝试计算SVGElement直接附加到 HTML DOM 并且没有 parent 的边界框,也会发生这种情况SVGSVGElement。示例(您可以在 ScratchpadShift+F4和 Firefox 中运行代码):

text直接附在body

这失败了,因为<html><body><g></g></body></html>不允许。

var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
document.body.appendChild(text)
text.getBBox()
/*
Exception: [Exception... "Failure"  nsresult: "0x80004005 (NS_ERROR_FAILURE)"  location: "JS frame :: Scratchpad/2 :: <TOP_LEVEL> :: line 3"  data: no]
*/

text附在svg

这行得通。

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
svg.appendChild(text);
document.body.appendChild(svg)
text.getBBox()
/*
[object SVGRect]
*/
于 2017-06-15T09:00:10.853 回答