旋转矩形的边界获取

4

我正在尝试获取 边界框 内实际旋转矩形的 位置

enter image description here

矩形被旋转了 120deg 我试图实现您在此处看到的蓝色轮廓

enter image description here

我成功使用矩阵将旋转效果实现,但其他部分还无法正确实现。
以下是我的代码:
let svg = document.querySelector('svg')
let overlay = document.querySelector('.overlay')
let rect = svg.children[0]

let bounds = rect.getBoundingClientRect()
let matrix = rect.getCTM()

overlay.style.top = bounds.top + 'px'
overlay.style.left = bounds.left + 'px'
overlay.style.width = bounds.width + 'px'
overlay.style.height = bounds.height + 'px'
overlay.style.transform = `matrix(${matrix.a},${matrix.b},${matrix.c},${matrix.d},0,0)`

http://jsfiddle.net/wjugqn31/67/


查看 https://dev59.com/tZ7ha4cB1Zd3GeqPl5yK 这个链接。这些信息足以计算你想要的内容吗? - MBo
在我的情况下,我不知道矩形本身的高度和宽度,我只知道边界框的宽度/高度,所以我认为这种情况下可能行不通。 - zaarr78
所以已知的数据只有边界框的宽度/高度和旋转角度吗?没有其他的了吗? - MBo
是的,我知道Boundingbox具有高度、宽度、顶部、左侧位置和最后的角度(120度)。没有别的。 - zaarr78
@MBo,我有这个问题的确切相反,如何获取未旋转矩形的边界。https://dev59.com/wlQJ5IYBdhLWcg3wVEV0 - 1.21 gigawatts
2个回答

9
已知数据:边界框宽度 W,高度 H,旋转角度 Fi
需要求解:旋转矩形顶点的坐标。
未知源矩形大小:w x h 该维度和旋转角度下的边界框大小: enter image description here
 H = w * Abs(Sin(Fi)) + h * Abs(Cos(Fi))
 W = w * Abs(Cos(Fi)) + h * Abs(Sin(Fi))
 denote 
 as = Abs(Sin(Fi))
 cs = Abs(Cos(Fi))

因此,我们可以解决线性方程组并获得(请注意Pi/4角的奇异性)。

 h = (H * cs - W * as) / (cs^2 - as^2)
 w = -(H * as - W * cs) / (cs^2 - as^2)

顶点坐标:

 XatTopEdge = w * cs      (AE at the picture)
 YatRightEdge = h * cs    (DH)
 XatBottomEdge = h * as   (BG)
 YatLeftEdge = w * as     (AF)

请注意,根据给定的数据,我们不能区分角度 Fi90+Fi,但这个事实可能不会影响解决方案(wh 也会互换)。

实现此链接的代码。 - KANE

0

我认为你可以直接获取rect的尺寸,然后对其应用变换。在summary中:

let rect = svg.children[0]
let matrix = rect.getScreenCTM()

overlay.style.top = '0'
overlay.style.left = '0'
overlay.style.width = `${rect.width.animVal.value}px`
overlay.style.height = `${rect.height.animVal.value}px`
overlay.style.transformOrigin = '0 0'
overlay.style.transform = `matrix(${matrix.a},${matrix.b},${matrix.c},${matrix.d},${matrix.e},${matrix.f})`

我真的很喜欢这个解决方案,它在简单形状上运行得非常好,但对于某些情况似乎不起作用,您可以在此处查看fiddle http://jsfiddle.net/wjugqn31/113/。 - zaarr78
@zaarr78 这是因为边框非常紧,而字母本身的坐标起始位置在 ~ 11,31。 你可以通过添加额外的偏移量到转换矩阵中 修正matrix(${matrix.a},${matrix.b},${matrix.c},${matrix.d},${matrix.e},${matrix.f}) translate(${bbox.x}px,${bbox.y}px) - ewcz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接