计算多个矩形的边界框(有和/或没有旋转)

问题描述 投票:0回答:1

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

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

这是一个例子:

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

旋转点功能直接来自konvajs网站(https://konvajs.org/docs/posts/Position_vs_Offset.html),我更新了一些细微的变化

javascript konvajs
1个回答
0
投票

这是我在一个应用程序中使用的utils函数版本,用于计算形状的bouding框。

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
  };
}

但是:ぁzxswい

© www.soinside.com 2019 - 2024. All rights reserved.