计算多个矩形的边界框(and/or 无旋转)

Compute bounding box of multiple rectangles (with and/or without rotation)

我正在尝试检索几个矩形的边界框(其中一些矩形已旋转)

我当前的实现适用于未旋转的矩形,但我不确定我是否有适用于具有旋转角度的矩形的正确公式。

这是一个例子:

https://codesandbox.io/embed/13z2p2w89q

旋转点功能直接取自 konvajs 网站 (https://konvajs.org/docs/posts/Position_vs_Offset.html),我对其进行了一些小改动

这是我在一个应用程序中用于计算形状边界框的 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
  };
}

演示:https://codesandbox.io/s/j28nz494r3