Rotation check in javascript

Asked

Viewed 386 times

3

Is there any way to check the rotation of a div in javascript, for example the verification of style left is offsetLeft, someone could tell me what the rotation would look like?

2 answers

5


Try this:

var el = document.getElementById("complex-transform");
var st = window.getComputedStyle(el, null);
var tr = st.getPropertyValue("-webkit-transform") ||
     st.getPropertyValue("-moz-transform") ||
     st.getPropertyValue("-ms-transform") ||
     st.getPropertyValue("-o-transform") ||
     st.getPropertyValue("transform") ||
     "fail...";

// With rotate(30deg)...
// matrix(0.866025, 0.5, -0.5, 0.866025, 0px, 0px)
console.log('Matrix: ' + tr);

// rotation matrix - http://en.wikipedia.org/wiki/Rotation_matrix

var values = tr.split('(')[1];
values = values.split(')')[0];
values = values.split(',');
var a = values[0];
var b = values[1];
var c = values[2];
var d = values[3];

var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));

// works!
console.log('Rotate: ' + angle + 'deg');

Demonstration

And for a more detailed explanation, follow the source of the code: CSS-Tricks published by Chris Coyier.

5

The mathematical principle turns out to be always the same, and the answer of @Gabriel Vítor already deals very well with the problem.

I leave a function based on jQuery to collect the rotation value of a given element:

Example in Jsfiddle

Function

function rotacaoEmGraus(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");

    var angle = 0;

    if (matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(','),
            angle = Math.round(Math.atan2(values[1], values[0]) * (180/Math.PI));
    }

    return (angle < 0) ? angle +=360 : angle;
}

Utilizing

var angulo = rotacaoEmGraus($('#bubu'));

Credits for the original @Twist feature version in this answer and @andreacanton in this answer of SOEN.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.