gpt4 book ai didi

javascript - 隐藏时获取 SVG 的 BBox

转载 作者:搜寻专家 更新时间:2023-11-01 05:31:02 26 4
gpt4 key购买 nike

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

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

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

有什么想法吗?

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

最好的问候

最佳答案

根据之前的答案,我在我的应用程序初始化上对 getBBox 进行了 monkeypatched,以便它可以透明地应用 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;
}
};

关于javascript - 隐藏时获取 SVG 的 BBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28282295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com