隐藏时的SVG的GetBBox [英] GetBBox of SVG when hidden

查看:282
本文介绍了隐藏时的SVG的GetBBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to solve this problem for more than one day now, but I can't find an answer. My problem is that I need to scale an SVG image (responsive design). I need to manipulate the SVG code on the client side, so embedding it via img tag is not an option. Therefore I tried to use an inline image instead. However, to scale it properly it seems that I need to set the viewBox property. The SVG files are generated by some software which can't set the bounding box on it's own, so my idea was to use JavaScript for that purpose.

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

The problem is that my software uses various tab controls from a library which I can't modify. I can't just get the bounding box, because it's not rendered initially and therefore I just get back zeros (in Chrome) or error messages (in Firefox).

我需要的是一种无需实际渲染对象即可获得边框大小的方法.该库用于显示和隐藏选项卡的display参数是不可能的.

What I need is a way to get the size of the bounding box without actually rendering the object. It is not possible to manipulate the display parameter, which the library uses to show and hide tabs.

有什么想法吗?

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

One idea was to copy the SVG into another, visible div, but I don't know if that would solve the problem. And I don't know how to do it.

最诚挚的问候

推荐答案

基于先前的答案,我在应用程序init上进行了getBBox的修补,以便透明地应用该hack.

Based on the previous answers, I monkeypatched getBBox on my app init so it will transparently apply the hack.

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

Now I can call getBBox directly on any element, whether it's attached or not.

_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;
  }
};

这篇关于隐藏时的SVG的GetBBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆