Skip to content Skip to sidebar Skip to footer

Compute Bounding Box Of Multiple Rectangles (with And/or Without Rotation)

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

Solution 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


Post a Comment for "Compute Bounding Box Of Multiple Rectangles (with And/or Without Rotation)"