旋转后获取div角落像素位置

6

当你在div上设置旋转弧度/角度后,如何计算其左上角、左下角、右上角和右下角的像素位置?

举个例子会更好理解。


除非你知道旋转的中心是什么,否则你无法计算角落。 - Alnitak
你能否构建一个使用案例(在jsfiddle或其他平台上),以便我们可以确定你的确切目标? - web-tiki
4
你接受的答案完全不正确。 - Alnitak
你还确定你接受的答案是正确的吗?它对你有用吗? - John Dvorak
我已经更新了我的被接受的答案,以反映我自己解决问题的方案。这个方案对我有效,并返回正确的结果。 - Raskolnikoov
3个回答

12
假设旋转是相对于中心进行的,四个角的坐标也都是相对于同一个原点。每个点 (±a, ±b),其中 a 和 b 是 div 的半宽和半高,都需要与变换矩阵相乘。
|  cos(theta)   -sin(theta) |
|  sin(theta)    cos(theta) |

例如:

x' = a * cos(theta) - b * sin(theta)
y' = a * sin(theta) + b * cos(theta)

NB:上述内容是针对笛卡尔坐标系的 - 根据需要反转 theta 项,以适用于DOM坐标系,其中y轴向下运行。


8

我对这里的答案感到困惑。被贬低的答案肯定是错误的,但我也对另一个答案感到困惑,因为它是一个非常好但非常纯粹的提示。那里的例子对于通常的Web开发人员来说仍然非常理论化。所以我结合了两个答案,并制作了一个可行的版本贴在下面。所以,对于那些也在寻找工作的JavaScript解决方案的人,这里是:

function getPixelsByAngle(x, y, width, height, angle) {
   var radians = angle * Math.PI / 180;
   return [      //upper left      [x + width/2 + width/-2 * Math.cos(radians) - height/-2 * Math.sin(radians), y + height/2 + width/-2 * Math.sin(radians) + height/-2 * Math.cos(radians)],
      //upper right
      [x + width/2 + width/2 * Math.cos(radians) - height/-2 * Math.sin(radians), y + height/2 + width/2 * Math.sin(radians) + height/-2 * Math.cos(radians)],
      //bottom right
      [x + width/2 + width/2 * Math.cos(radians) - height/2 * Math.sin(radians), y + height/2 + width/2 * Math.sin(radians) + height/2 * Math.cos(radians)],
      //bottom left
      [x + width/2 + width/-2 * Math.cos(radians) - height/2 * Math.sin(radians), y + height/2 + width/-2 * Math.sin(radians) + height/2 * Math.cos(radians)],
   ];
}

1
x/y参数是给定元素中心的坐标吗? - Jayant Bhawal
提升一下,x/y 是中心吗? - Alex Nelson
1
不,x/y是元素左上角的位置。因此它指示了元素在坐标系上的位置。因此,结果还包含该坐标系上的位置。然而,实际上计算时并不需要x和y。你可以从整个函数中简单地删除x和y变量,然后只得到角落移动的距离与旋转。旋转点始终为元素的中心。 - user1030151
谢谢您的回答。这个答案让我节省了很多时间 - 而且还有效! - czinkipuczczum karamba
很棒的函数,运行非常好。 - user1620090

-3

这解决了我在旋转后计算新像素位置的问题。我创建了一个函数,可以传入x/y位置、div的一半宽度/高度和新的旋转角度。

function getPixelsByAngle(x,y,halfWidth,halfHeight,angle){
   var bounds = [
      //upper left
      [x + (halfWidth) * Math.cos(angle) - (halfHeight) * Math.sin(angle) + halfWidth, y + (halfHeight) * Math.cos(angle) + (halfWidth) * Math.sin(angle) + halfHeight],
      //upper right
      [x - (halfWidth) * Math.cos(angle) - (halfHeight) * Math.sin(angle) + halfWidth, y + (halfHeight) * Math.cos(angle) - (halfWidth) * Math.sin(angle) + halfHeight],
      //bottom right
      [x - (halfWidth) * Math.cos(angle) + (halfHeight) * Math.sin(angle) + halfWidth, y - (halfHeight) * Math.cos(angle) - (halfWidth) * Math.sin(angle) + halfHeight],
      //bottom left
      [x + (halfWidth) * Math.cos(angle) + (halfHeight) * Math.sin(angle) + halfWidth, y - (halfHeight) * Math.cos(angle) + (halfWidth) * Math.sin(angle) + halfHeight]
   ];
   return bounds;
}

3
我认为你使用我提供的信息,然后将其转化为一个(写得很差的)答案并接受它是不合适的。 - Alnitak

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