Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain the Actual Left,Top position of a rotated div

If I have a div that is rotated 45 degrees and its attributes are: left: 0, top: 0, width: 100px, height: 100px. Can I obtain the actual x,y position of the divs top left corner?

When the div is rotated, the top left corner sits at about -10px,-10px(guess). But I am attempting to calculate the actual top left corners x,y position for a web application.

Maybe you know of a mathematical formula that can determine the top left corners x,y position? Or maybe a javascript attribute will give me it? Such as div.style.actualLeft;?

like image 334
sazr Avatar asked Mar 20 '12 22:03

sazr


1 Answers

If it is static 45 degrees and the origin of the rotation is in the center then you'll only have to calculate this once which is:

sqrt((width/2)^2+(height/2)^2)
sqrt(50^2+50^2) // Pythagorean theorem

which is 70,71067811865475

So compared to the origin, x wise it's negative 70,7106... and y wise it's 0.

If you are going to rotate it dynamicly so you must know it all the time then voila! Behold!

compute the distance once, sqrt(50^2+50^2), then multiply this by the rotation you're adding to the cube + 135 degrees (cause it's top left). (90 = straight up, + 45 = 135)

so to get the same answer I just said it would be:

var dist=Math.sqrt(50^2+50^2);
var degtorad=Math.PI/180;

var x = Math.cos(degtorad * (135+rotation)) * dist;
var y = Math.sin(degtorad * (135+rotation)) * dist;

Now x & y will be relative to the origin. If you need more help then be more specific in your question so we can answer better, help us to help you.

quick calculation:

rotation=45
135+45 = 180

Math.cos(degtorad * 180)) = -1
Math.sin(degtorad * 180)) = 0;

x = -1 * dist = -70,71067811865475
y = 0 * dist = 0

and voila it's like I said for calculating the static in the beginning, I just didn't use any cos / sin for that.. but this works aswell. (-75 works aswell)

like image 50
Harry Svensson Avatar answered Nov 15 '22 06:11

Harry Svensson