簡體   English   中英

以 svg 為單位獲取 g 邊界框

[英]Get g bounding box in svg units

我正在嘗試在Javascript 中實現一個菜單,其中單個菜單項svg:g 要將一個項目標記為已選擇,我想在menu-item頂部移動另一個svg:g

為此,我需要獲取菜單項的邊界框 (= svg:g ),以便我可以將 rect (x, y, width, height) 應用於另一個。 我還沒有找到一種方便的方法來獲取svg:g的邊界框。

我能想到的唯一方法是遞歸到子級並手動計算邊界框(近似值)。 有沒有更優雅的方式?

您應該能夠使用組元素的getBBox方法。
例如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