Is there any way to check the rotation of a div
in javascript
, for example checking style
left
is offsetLeft
, could someone tell me how the rotation would look?
Is there any way to check the rotation of a div
in javascript
, for example checking style
left
is offsetLeft
, could someone tell me how the rotation would look?
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');
And for a more detailed explanation, the source code follows: CSS-Tricks posted by Chris Coyier .
The mathematical principle turns out to be always the same, and the answer from @Gabriel Vítor already handles very well with the problem.
I left a jQuery-based function to collect the value of the rotation of a given element:
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;
}
var angulo = rotacaoEmGraus($('#bubu'));
Credits for the original version of the function for @Twist in this answer and @andreacanton in this SOEN response.