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.
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.
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)],
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With