简体   繁体   English

以 svg 为单位获取 g 边界框

[英]Get g bounding box in svg units

I am trying to implement a menu in Javascript with single menu-items being svg:g .我正在尝试在Javascript 中实现一个菜单,其中单个菜单项svg:g To mark an item as selected I would like to move another svg:g on top of the menu-item .要将一个项目标记为已选择,我想在menu-item顶部移动另一个svg:g

For this I need to get the bounding box of the menu-item (= svg:g ) so I can apply the rect (x, y, width, height) to the other.为此,我需要获取菜单项的边界框 (= svg:g ),以便我可以将 rect (x, y, width, height) 应用于另一个。 I have not found a convenient way yet, for getting the bounding box of a svg:g .我还没有找到一种方便的方法来获取svg:g的边界框。

The only way I can think of would be recursing into the children and calculating the bounding box (approximation) by hand.我能想到的唯一方法是递归到子级并手动计算边界框(近似值)。 Is there a more elegant way?有没有更优雅的方式?

You should just be able to use the getBBox method of your group element.您应该能够使用组元素的getBBox方法。
eg http://jsfiddle.net/PFnre/1/例如http://jsfiddle.net/PFnre/1/

 var root = document.createElementNS("http://www.w3.org/2000/svg", "svg"); document.body.appendChild(root); var g = document.createElementNS("http://www.w3.org/2000/svg", "g"); 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"); 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM