获取元素的边界框以对其进行转换 [英] Get bounding box of element accounting for its transform
本文介绍了获取元素的边界框以对其进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出此SVG:
<svg xmlns="http://www.w3.org/2000/svg">
<rect width="50" height="50"
transform="translate(75,75) rotate(45) translate(-25,-25)" />
<script>
var bb = document.querySelector('rect').getBBox();
console.log([bb.x,bb,y,bb.width,bb.height]);
</script>
</svg>
结果输出为[0, 0, 50, 50]
.
期望的结果是[39.645,39.645,70.711,70.711]
.
The resulting output is [0, 0, 50, 50]
.
The desired result is [39.645,39.645,70.711,70.711]
.
计算元素相对于其父元素的边界框的最简单,最有效的方法是什么?
What's the simplest, most efficient way to calculate the bounding box of an element with respect to its parent element?
以下是到目前为止我提出的最佳答案,但是有两个问题:
Below is the best answer I've come up with so far, but there are two problems:
- 要想更好地处理,似乎需要做很多工作,并且
- 在 此演示 中可以看到,它不一定是最小边界框(请注意上面的圆圈),因为旋转的轴对齐边界框的轴对齐边界框始终会增大尺寸.
// Calculate the bounding box of an element with respect to its parent element
function transformedBoundingBox(el){
var bb = el.getBBox(),
svg = el.ownerSVGElement,
m = el.getTransformToElement(el.parentNode);
// Create an array of all four points for the original bounding box
var pts = [
svg.createSVGPoint(), svg.createSVGPoint(),
svg.createSVGPoint(), svg.createSVGPoint()
];
pts[0].x=bb.x; pts[0].y=bb.y;
pts[1].x=bb.x+bb.width; pts[1].y=bb.y;
pts[2].x=bb.x+bb.width; pts[2].y=bb.y+bb.height;
pts[3].x=bb.x; pts[3].y=bb.y+bb.height;
// Transform each into the space of the parent,
// and calculate the min/max points from that.
var xMin=Infinity,xMax=-Infinity,yMin=Infinity,yMax=-Infinity;
pts.forEach(function(pt){
pt = pt.matrixTransform(m);
xMin = Math.min(xMin,pt.x);
xMax = Math.max(xMax,pt.x);
yMin = Math.min(yMin,pt.y);
yMax = Math.max(yMax,pt.y);
});
// Update the bounding box with the new values
bb.x = xMin; bb.width = xMax-xMin;
bb.y = yMin; bb.height = yMax-yMin;
return bb;
}
推荐答案
您需要使用的只是这个简单的Javascript函数:
All you need to use is this simple Javascript function:
object.getBoundingClientRect();
它受以下支持:
Chrome Firefox (Gecko) Internet Explorer Opera Safari
1.0 3.0 (1.9) 4.0 (Yes) 4.0
请在此处查看有关此内容的更多信息. 链接
Look here for more about it. Link
这篇关于获取元素的边界框以对其进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文