Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get div corners pixel positions after rotation

Tags:

javascript

css

how can i calculate top-left, bottom-left, top-right, bottom-right pixel positions of a div after you have set a rotation radian/degree on it?

An example would be helpful.

like image 345
Raskolnikoov Avatar asked Jul 18 '14 10:07

Raskolnikoov


2 Answers

Assuming rotation relative to the center and coordinates of the four corners also relative to that same origin, each point (±a, ±b) where a and b are the half-width and half-height of the div needs to be multiplied by the transformation matrix:

|  cos(theta)   -sin(theta) |
|  sin(theta)    cos(theta) |

e.g.:

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

NB: the above is for cartesian coordinates - invert the theta terms as necessary for DOM coordinates where the y axis runs downwards.

like image 115
Alnitak Avatar answered Nov 12 '22 18:11

Alnitak


I was confused about the answers here. The down-voted answer is definitely wrong but I also struggled with the other answer because it's a very good but very pure hint. The example there is still very theoretical for a usual web developer. So I combined both answers and made a working version of the down-voted example. So for those who also search for a working javascript solution. Here it is:

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)],
   ];
}
like image 26
user1030151 Avatar answered Nov 12 '22 18:11

user1030151