首页 > 解决方案 > 获取旋转矩形的边界

问题描述

我试图positionbounding box.

在此处输入图像描述

矩形旋转了120deg

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

在此处输入图像描述

我设法得到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/

标签: mathsvgrotationgeometrysvg-transforms

解决方案


已知数据:边界框宽度W、高度H、旋转角度Fi
需要:旋转矩形顶点的坐标。

未知源矩形大小:w x h

此尺寸和旋转角度的边界框尺寸:

在此处输入图像描述

 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但这一事实可能不会影响解决方案(w并且h也会相互交换)


推荐阅读