2016-08-30 127 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 –

相關問題