如何使用Javascript测量旋转元素的宽度和高度?

4

当我旋转选择的div时,我的设计接口存在一个bug,这时选定div的宽度和高度是错误的。

以下是我已有的结构示意图和我想要的另一个示意图。

enter image description here

我希望使用Javascript找到公式,你能告诉我如何编写吗?

PS:我已经拥有第一个结构示意图的角度、宽度和高度,无需重新计算。


3
请看这个答案 - DarkBee
@DarkBee 这是JSFiddle建议的代码,不幸的是它无法正常工作。当你将其旋转到0度时,高度和宽度会发生变化(应该始终保持在200)。 - Hiroyuki Nuri
2个回答

3
如果您需要方程式,那么这里就有了。
w-y*sin(theta) = x*cos(theta)
h-y*cos(theta) = x*sin(theta)

在这里,

w = given width
h = given height
x = width you need
y = height you need
theta = angle

一点三角知识可谓极有用处。

解决这个同时方程的答案是 -

2x = (w+h)/(cos(theta)+sin(theta)) + (w-h)/(cos(theta)-sin(theta))
2y = (w+h)/(cos(theta)+sin(theta)) - (w-h)/(cos(theta)-sin(theta))

可以随意转换为数学函数。


3

Widthheight在旋转元素时不会改变,这个问题可以通过使用下面的方法获取值来解决,而且效果也是一样的。请通过dom获取以下值:

  1. offsetWidth
  2. offsetHeight

var rot =document.getElementById("rot");
console.log(rot.offsetWidth,rot.offsetHeight)
#rot{
width:100px;
height:40px;
background-color:pink;
transform:rotate(30deg)
}
<div id="rot"></div>


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