我正在尝试检索几个矩形的边界框(其中一些矩形是旋转的)
我当前的实现方式适用于未旋转的矩形,但是我不确定对于具有旋转角度的矩形是否具有正确的公式。
这里是一个例子:
https://codesandbox.io/embed/13z2p2w89q
旋转点功能直接来自konvajs网站(https://konvajs.org/docs/posts/Position_vs_Offset.html),我进行了一些细微的更新
答案 0 :(得分:0)
这是我在一个应用程序中用于计算形状绑定框的utils函数版本。
export function degToRad(angle) {
return angle / 180 * Math.PI;
}
export function getShapeRect(shape) {
const angleRad = degToRad(shape.rotation);
const x1 = shape.x;
const y1 = shape.y;
const x2 = x1 + shape.width * Math.cos(angleRad);
const y2 = y1 + shape.width * Math.sin(angleRad);
const x3 =
shape.x +
shape.width * Math.cos(angleRad) +
shape.height * Math.sin(-angleRad);
const y3 =
shape.y +
shape.height * Math.cos(angleRad) +
shape.width * Math.sin(angleRad);
const x4 = shape.x + shape.height * Math.sin(-angleRad);
const y4 = shape.y + shape.height * Math.cos(angleRad);
const leftX = Math.min(x1, x2, x3, x4);
const rightX = Math.max(x1, x2, x3, x4);
const topY = Math.min(y1, y2, y3, y4);
const bottomY = Math.max(y1, y2, y3, y4);
return {
x: leftX,
y: topY,
width: rightX - leftX,
height: bottomY - topY
};
}
export function getBoundingBox(shapes) {
let x1 = 9999999999;
let y1 = 9999999999;
let x2 = -999999999;
let y2 = -999999999;
shapes.forEach(shape => {
const rect = getShapeRect(shape);
x1 = Math.min(x1, rect.x);
y1 = Math.min(y1, rect.y);
x2 = Math.max(x2, rect.x + rect.width);
y2 = Math.max(y2, rect.y + rect.height);
});
return {
x: x1,
y: y1,
width: x2 - x1,
height: y2 - y1,
rotation: 0
};
}