获取旋转矩形的内框 - JavaScript

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

我正在开发一款包含旋转矩形的游戏。我想找到可以放入其中的最大可能非旋转矩形的确切尺寸。到目前为止,我看到的所有问题都涉及找到bounding 框。然而,就我而言,我想找到旋转矩形的inner框。

大多数人想要的:

我想要的:

我已经想出如何用这段代码找到矩形的边界框...

// JavaScript Code

const AVERAGE = (this.height + this.width) / 2

box.width = AVERAGE / 2 + Math.abs(Math.sin(ANGLE) * AVERAGE)
box.height = AVERAGE / 2 + Math.abs(Math.cos(ANGLE) * AVERAGE)

...但我不知道如何获得inner 盒子。任何帮助将不胜感激。

提前致谢。

javascript rotation angle bounding-box
1个回答
0
投票

要找到可以放入旋转矩形内的最大可能的非旋转矩形,您可以首先使用您提供的代码计算边界框的尺寸。

然后,要找到可以放入旋转矩形内的最大可能非旋转矩形的尺寸,您需要计算可以放入边界框内的最大非旋转矩形的尺寸。

您可以通过比较旋转矩形和边界框的纵横比来做到这一点。如果旋转矩形的纵横比大于边界框的纵横比,则边界框内可容纳的最大非旋转矩形的宽度将等于边界框的宽度,高度将通过使用旋转矩形的纵横比缩放宽度来计算。如果旋转矩形的纵横比小于边界框的纵横比,则边界框内可容纳的最大非旋转矩形的高度将等于边界框的高度,宽度将通过使用旋转矩形的纵横比缩放高度来计算。

这里是找到可以放入旋转矩形内的最大可能非旋转矩形尺寸的代码:

const AVERAGE = (this.height + this.width) / 2;
const boundingBoxWidth = AVERAGE / 2 + Math.abs(Math.sin(ANGLE) * AVERAGE);
const boundingBoxHeight = AVERAGE / 2 + Math.abs(Math.cos(ANGLE) * AVERAGE);

const rotatedAspectRatio = this.width / this.height;
const boundingBoxAspectRatio = boundingBoxWidth / boundingBoxHeight;

let innerWidth, innerHeight;

if (rotatedAspectRatio > boundingBoxAspectRatio) {
  innerWidth = boundingBoxWidth;
  innerHeight = boundingBoxWidth / rotatedAspectRatio;
} else {
  innerHeight = boundingBoxHeight;
  innerWidth = boundingBoxHeight * rotatedAspectRatio;
}

// innerWidth and innerHeight are the dimensions of the largest possible non-rotated rectangle that could fit inside the rotated rectangle

注意上面代码中this.width和this.height指的是旋转矩形的尺寸

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