SVGGraphicsElement: getBBox() 方法
SVGGraphicsElement.getBBox() 方法允許我們確定物件最小外接矩形的座標。返回的座標是相對於當前的 SVG 座標系(在目標元素包含的所有元素上應用了所有幾何屬性之後)。
注意:getBBox() 必須在呼叫時返回實際的邊界框,即使元素尚未渲染。它也不考慮應用於元素或其父元素的任何變換。
注意:getBBox 返回的值與 getBoundingClientRect() 返回的值不同,後者返回的值是相對於視口的。
語法
js
getBBox()
getBBox(options)
引數
options實驗性 可選-
一個選項字典,用於控制邊界框中應包含元素的哪些部分。可用選項為:
返回值
返回值是一個 SVGRect 物件,該物件定義了邊界框。此值與應用於它或其父元素的任何變換屬性無關。
示例
HTML
html
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<g id="group_text_1">
<text x="5" y="16" transform="scale(2, 2)">Hello World!</text>
<text x="8" y="32" transform="translate(0 20) scale(1.25 1)">
Hello World Again!
</text>
</g>
<!-- Shows BBox in green -->
<rect id="rect_1" stroke="green" stroke-width="3" fill="none"></rect>
<!-- Shows BoundingClientRect in red -->
<rect id="rect_2" stroke="red" stroke-width="3" fill="none"></rect>
</svg>
JavaScript
js
const rectBBox = document.querySelector("#rect_1");
const rectBoundingClientRect = document.querySelector("#rect_2");
const groupElement = document.querySelector("#group_text_1");
const bboxGroup = groupElement.getBBox();
rectBBox.setAttribute("x", bboxGroup.x);
rectBBox.setAttribute("y", bboxGroup.y);
rectBBox.setAttribute("width", bboxGroup.width);
rectBBox.setAttribute("height", bboxGroup.height);
const boundingClientRectGroup = groupElement.getBoundingClientRect();
rectBoundingClientRect.setAttribute("x", boundingClientRectGroup.x);
rectBoundingClientRect.setAttribute("y", boundingClientRectGroup.y);
rectBoundingClientRect.setAttribute("width", boundingClientRectGroup.width);
rectBoundingClientRect.setAttribute("height", boundingClientRectGroup.height);
規範
| 規範 |
|---|
| Scalable Vector Graphics (SVG) 2 # __svg__SVGGraphicsElement__getBBox |
瀏覽器相容性
載入中…