2014-11-08 19 views
0

請參考下面的代碼,所述邊界框的位置是不實際的呈現該組的元件中的位置。如何獲取組元素渲染位置?

該組元素可以被用來構造一個非常複雜的單元像坦克/船舶用大炮。 和組元素沒有X或Y屬性,以幫助移動內部元件,所以我必須使用變換來移動坦克/船舶。

但是,我意識到,當我翻譯組,邊框從來沒有反映真實的渲染位置更多的,沒有任何一個有任何想法如何獲得該組的實際渲染位置?

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); 

回答

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/