0
votes

I have a div element that gets rotated with -webkit-transform: rotate(45deg). If I try to access it's current position after rotation like this

var x = $('#tap-area').offset().left;
var y = $('#tap-area').offset().top;

it returns me not the actual values of where the original top left corner is, but where is the top left corner of the bounding box of the whole div (which is physically furthest top left, outside of the DIV).

How can I calculate/get the original top left corner of the div after it gets rotated

Eg: If I rotate it by 90deg, the value I would like to get now would be top right. If I rotate it by 180deg, the value I would like to get now would be bottom right.

I need this, so I could set another DIV element to always stay attached to the original top left corner of the element, so that it would change it's position depending on how it was rotated.

Thanks.

2

2 Answers

3
votes

You can always get the absolute position of an element using:

<element>.getBoundingClientRect()

This gives you the AABB (Axis Aligned Bounding Box, or Min-Max-Box) with the top left corner of the screen as origin. (MDN)

If you need to access the position of the top left corner of your element you can rotate its original position vector too, what is a simple matrix multiplication. You should than keep in mind that the center of rotation is by default the element's center, but it also possible to set this to a different location with css.

Good Luck!

0
votes

This is a solution I come to after being faced with the same problem:

// Initial data with TOP AND LEFT OF THE BOUNDING BOX (not x,y of top left point of     the box but left margin of the bounding box   and top margin of the bounding    box)

var top  = Math.ceil($('#' + id).position().top);
var left = Math.ceil($('#' + id).position().left);
var wi   = $('#' + id).css("width").replace("px","");
var he   = $('#' + id).css("height").replace("px","");
var rot  = $(this).data(id + ".ROTACION"); //There I have the applied rotation stored ...

// CALULATIONS

var swapheightwidth= false;

    //Let's keept it first cuad. 

if (rot > 270)
{
    rot = rot - 270;
    swapheightwidth= = true;
}
else if (rot > 180) 
{
    rot = rot - 180;
}
else if (rot > 90) 
{
    swapheightwidth= = true;
    rot = rot - 90;
}

if (swapheightwidth)
{
    var calculatedX=  left + (wi * sin(rot)); 
    var calculatedY=  top + (wi * cos(rot));
}
else
{
    var calculatedX=  left + (he * sin(rot)); 
    var calculatedY=  top + (he * cos(rot));
}

var xbott = left;
var ybott =  Math.ceil(calculatedY);

var xtop=  Math.ceil(calculatedX);
var ytop= top;

    // FINAL CALCULATED POINTS
// xtop  ytop  -> top left
// xbott  ybott   -> bottomleft 

function sin(x) {
    return Math.sin(x / 180 * Math.PI);
}

function cos(x) {
    return Math.cos(x / 180 * Math.PI);
}

Cheers