获取旋转矩形的边界

时间:2018-07-22 07:04:33

标签: math svg rotation geometry svg-transform

我正在尝试获取position内实际旋转矩形的bounding box

enter image description here

矩形旋转120deg

我正在尝试实现蓝色轮廓,您可以在此处看到

enter image description here

我设法使用rotation使matrix正确,但是我无法正确处理其余部分。

这是我的代码

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/

2 个答案:

答案 0 :(得分:2)

已知数据:包围盒宽度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也会互相交换)

答案 1 :(得分:1)

我认为您可以直接获取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})` 的尺寸,然后对其进行转换。在summary中:

map_set