2016-08-30 139 views
0

我在组元素和rect元素上做getBBox()。 group元素和rect元素具有相同的位置和大小。组getBBox()总是将x,y设置为0,0,而rect则给出它在外部组中的实际位置。为什么?组元素的getBBox()不应该像父元素一样在其父元素内部放回它的边界? 下面的HTML输出以下控制台:组元素的SVG getBBox()给出了具有相同大小和位置的矩形元素的不同结果

SVGRect { x: 0, y: 0, width: 800, height: 400}<br/> 
SVGRect { x: 0, y: 0, width: 100, height: 100}<br/> 
SVGRect { x: 100, y: 200, width: 100, height: 100}<br/> 

var superg = d3.select("#canvasHolder").append("svg").attr("width", 800).attr("height", 400) 
 
       .append("g").attr("id", "superg") 
 
    
 
superg.append("rect").attr("width", 800).attr("height", 400).style("fill", "blue").style("fill-opacity", 0.2) 
 
superg.append("rect").attr("width", 100).attr("height", 100).style("fill", "red").style("fill-opacity", 0.2).attr("id", "rect").attr("x", 100).attr("y", 200) 
 
    
 
superg.append("g").attr("transform", "translate(100, 200)").attr("id", "g") 
 
     .append("rect").attr("cx", 0).attr("cy", 0).attr("width", 100).attr("height", 100) 
 
    
 
console.log(d3.select("#superg").node().getBBox()) 
 
console.log(d3.select("#g").node().getBBox()) 
 
console.log(d3.select("#rect").node().getBBox())
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 
<div id="canvasHolder"></div>

我本来以为该组元素应该有X和Y的值相同,rect元素。为什么不是这样?

回答

2

我们需要查看生成的SVG来找到答案。我将专注于内部<g id="g">并将其余部分删除。

<g transform="translate(100, 200)" id="g"> 
    <rect cx="0" cy="0" width="100" height="100"></rect> 
</g> 

你从一个元素上调用getBBox()不包括元素上的任何transform属性的效果背面的边界矩形值。它仅从其子女的边界框计算得出。

参见:the definition of getBBox() in the SVG 1.1 spec

所以呼吁组getBBox()仅包括其子<rect>的尺寸,因此,(0,0,100,100)。但<rect>受其父母提供的转换影响,所以你得到(100,200,100,100)当你得到的Bbox的。

+0

因此,该组的bbox的x和y值永远不是相对于封装元素,它只显示其内容的左上角相对于它自己呢? – j18434

+0

如果我理解正确,那么是的。该组与坐标位于不同的坐标空间中。 rect位于父元素(组)的变换所创建的坐标空间中。在组的坐标空间中,矩形为0,0。但在协议的坐标空间,它是在100,200 –

相关问题