问题
I am trying to retrieve the bounding box of several rectangles (some of these rectangles are rotated)
My current implementation works for rectangles that are not rotated, but I am not sure if I have the right formula for the ones with a rotation angle.
Here is an example:
https://codesandbox.io/embed/13z2p2w89q
The rotate point function was taken directly from the konvajs website (https://konvajs.org/docs/posts/Position_vs_Offset.html) and I updated it with some minor changes
回答1:
Here is my version of utils functions that I was using in one app for calculating the bouding box of shapes.
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
};
}
Demo: https://codesandbox.io/s/j28nz494r3
来源:https://stackoverflow.com/questions/55941310/compute-bounding-box-of-multiple-rectangles-with-and-or-without-rotation