旋转后得到div角像素位置

Ras*_*oov 3 javascript css3

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

一个例子会有所帮助.

Aln*_*tak 9

假设旋转相对于中心和四个角的坐标也相对于相同的原点,每个点(±a, ±b),其中ab是需要通过变换矩阵相乘的半宽度和的div半高:

|  cos(theta)   -sin(theta) |
|  sin(theta)    cos(theta) |
Run Code Online (Sandbox Code Playgroud)

例如:

x' = a * cos(theta) - b * sin(theta)
y' = a * sin(theta) + b * cos(theta)
Run Code Online (Sandbox Code Playgroud)

注意:上面是笛卡尔坐标 - thetay轴向下运行的DOM坐标中根据需要反转项.


use*_*151 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)],
   ];
}
Run Code Online (Sandbox Code Playgroud)


Ras*_*oov -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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为您不适合使用我提供的信息,然后将其转化为(写得不好的)答案,然后接受它 (3认同)