隐藏时,SVG的GetBBox

我现在试图解决这个问题超过一天,但我找不到答案。 我的问题是我需要扩展SVG图像(响应式设计)。 我需要在客户端操作SVG代码,因此通过img标签嵌入它不是一种选择。 因此我尝试使用内嵌图像。 但是,为了正确地缩放它,似乎我需要设置viewBox属性。 SVG文件是由某些软件生成的,这些软件无法自行设置边界框,因此我的想法是为此目的使用JavaScript。

问题是我的软件使用库中的各种选项卡控件,我无法修改。 我不能只获得边界框,因为它最初没有呈现,因此我只是回到零(在Chrome中)或错误消息(在Firefox中)。

我需要的是一种获取边界框大小而不实际渲染对象的方法。 无法操纵显示参数,库用于显示和隐藏选项卡。

有任何想法吗?

一个想法是将SVG复制到另一个可见的div中,但我不知道这是否能解决问题。 而且我不知道该怎么做。

最好的祝福

你可以将它克隆到一个可见的svg然后getBBox。

加入你的html:

添加到您的JavaScript:

 function getBBox(elem){ var svg1 = document.getElementById('svg1'), e = elem.cloneNode(true); e.style.display = "inline"; svg1.appendChild(e); var b = e.getBBox(); svg1.removeChild(e); return b; } 

cuixiping的答案作为一个function:

 function svgBBox (svgEl) { let tempDiv = document.createElement('div') tempDiv.setAttribute('style', "position:absolute; visibility:hidden; width:0; height:0") document.body.appendChild(tempDiv) let tempSvg = document.createElementNS("http://www.w3.org/2000/svg", 'svg') tempDiv.appendChild(tempSvg) let tempEl = svgEl.cloneNode(true) tempSvg.appendChild(tempEl) let bb = tempEl.getBBox() document.body.removeChild(tempDiv) return bb } 

基于之前的答案,我在我的应用程序初始化monkeypatched getBBox ,因此它将透明地应用hack。

现在我可以直接在任何元素上调用getBBox ,无论它是否附加。

 _getBBox = SVGGraphicsElement.prototype.getBBox; SVGGraphicsElement.prototype.getBBox = function() { var bbox, tempDiv, tempSvg; if (document.contains(this)) { return _getBBox.apply(this); } else { tempDiv = document.createElement("div"); tempDiv.setAttribute("style", "position:absolute; visibility:hidden; width:0; height:0"); if (this.tagName === "svg") { tempSvg = this.cloneNode(true); } else { tempSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); tempSvg.appendChild(this.cloneNode(true)); } tempDiv.appendChild(tempSvg); document.body.appendChild(tempDiv); bbox = _getBBox.apply(tempSvg); document.body.removeChild(tempDiv); return bbox; } };