24

I'm having a problem with getting the position of a div after rotate filter is applied to it. I have the position of one end, its height, and the angle by which it is rotated, but after checking what this filter actually does on MDN ("[cos(angle) sin(angle) -sin(angle) cos(angle) 0 0]") I still don't know how to crack it.

Example :

enter image description here

The div I'm interested in is the dashed line. Its styling at that moment was :

left: 80px; top: 12px; height: 69.5122px; width: 2px; -moz-transform: rotate(-1.21366rad);

(top/left describe the position of its beginning.) I'm trying to get the top/left position of its end.

Dave Sag
  • 13,266
  • 14
  • 86
  • 134
sasklacz
  • 3,610
  • 10
  • 39
  • 58
  • 1
    after refreshing my mathematics knowledge I've came up with something like this : var x = termin.top + Math.cos(angle) * div.height; var y = div.left + Math.sin(angle) * div.height; Can anyone confirm if that's the proper solution ? – sasklacz Jun 27 '12 at 15:33

2 Answers2

16

Per your current Question and your requested confirmation of:

var x = termin.top + Math.cos(angle) * div.height;
var y = div.left + Math.sin(angle) * div.height;

The solution can be found in this other SO Answer for a different question, enhanced here:

// return an object with full width/height (including borders), top/bottom coordinates
var getPositionData = function(el) {
    return $.extend({
        width: el.outerWidth(false),
        height: el.outerHeight(false)
    }, el.offset());
};

// get rotated dimensions   
var transformedDimensions = function(el, angle) {
    var dimensions = getPositionData(el);
    return {
        width: dimensions.width + Math.ceil(dimensions.width * Math.cos(angle)),
        height: dimensions.height + Math.ceil(dimensions.height * Math.cos(angle))
    };
};


Here's an interactive jsFiddle that provides real-time updates for getPositionData(); function.
You'll be able to see the top and left values at the end of the CSS3 Rotation process you control.

Reference:   jsFiddle

Status Update: The above jsFiddle works great for 0-90deg and can be approved upon for all angles and different units such as rad, grad, and turn.

Community
  • 1
  • 1
arttronics
  • 9,957
  • 2
  • 26
  • 62
5

Try using element.getBoundingClientRect()

According to MDN:

Starting in Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0) , the effect of CSS transforms is considered when computing the element's bounding rectangle.

pozs
  • 34,608
  • 5
  • 57
  • 63
  • 1
    Do we know what other browsers take consideration of transforms with `getBoundingClientRect`? Most importantly: at which point IE does? Does it work with IE9? – Jimbo Jonny Feb 15 '16 at 19:56
  • @JimboJonny [from my testing](https://jsfiddle.net/hhwrv5ov/) is seems IE9 also takes transforms into consideration (but rounds the results to whole pixels). IE10 works like any other browsers (does not round results). – pozs Feb 16 '16 at 09:06