【问题标题】:How to get group element render position?如何获取组元素渲染位置?
【发布时间】:2015-01-04 22:43:42
【问题描述】:

参考下面的代码,边界框的位置并不是该组元素的实际渲染位置。

组元素可用于构建非常复杂的单元,例如带有大炮的坦克/舰船。 并且 group 元素没有 X 或 Y 属性来帮助移动内部元素,所以我必须使用变换来移动 Tank / Ship。

但是,我意识到当我翻译组时,边界框不再反映真实的渲染位置,有没有人知道如何获得组的实际渲染位置?

http://jsfiddle.net/k4uhwLj4/

var root = document.createElementNS("http://www.w3.org/2000/svg", "svg");
root.style.width = '500px';
root.style.height = '500px';
document.body.appendChild(root);

var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
g.setAttributeNS(null, 'transform', 'translate(50, 50)');
root.appendChild(g);

var r = document.createElementNS("http://www.w3.org/2000/svg", "rect");
r.setAttribute("x", "50");
r.setAttribute("y", "60");
r.setAttribute("width", "100");
r.setAttribute("height", "110");
r.setAttribute("fill", "blue");
r.setAttributeNS(null, 'transform', 'translate(50, 50)');
g.appendChild(r);

var c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", "150");
c.setAttribute("cy", "140");
c.setAttribute("r", "60");
c.setAttribute("fill", "red");
g.appendChild(c);

var bbox = g.getBBox();

var o = document.createElementNS("http://www.w3.org/2000/svg", "rect");
o.setAttribute("x", bbox.x);
o.setAttribute("y", bbox.y);
o.setAttribute("width", bbox.width);
o.setAttribute("height", bbox.height);
o.setAttribute("stroke", 'black')
o.setAttribute("fill", 'none');
root.appendChild(o);

【问题讨论】:

    标签: svg bounding-box


    【解决方案1】:

    根据这篇文章,.getBBox() 方法不考虑转换(按规范):

    How is the getBBox() SVGRect calculated?

    要解决这个问题,您可以添加一个没有转换属性的父 g

    var parentG = document.createElementNS("http://www.w3.org/2000/svg", "g");
    root.appendChild(parentG);
    
    var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
    g.setAttributeNS(null, 'transform', 'translate(50, 50)');
    parentG.appendChild(g);
    

    http://jsfiddle.net/sydgc091/

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 1970-01-01
      • 2021-12-09
      • 2019-03-15
      • 2012-07-06
      • 2019-02-10
      • 1970-01-01
      • 2010-10-06
      相关资源
      最近更新 更多