我正在使用的代码found at CSS-Tricks来获得当前的旋转变换(在CSS)用JavaScript。
JavaScript函数:
function getCurrentRotation( elid ) {
var el = document.getElementById(elid);
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...";
if( tr !== "none") {
console.log('Matrix: ' + tr);
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 scale = Math.sqrt(a*a + b*b);
// arc sin, convert from radians to degrees, round
/** /
var sin = b/scale;
var angle = Math.round(Math.asin(sin) * (180/Math.PI));
/*/
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
/**/
} else {
var angle = 0;
}
// works!
console.log('Rotate: ' + angle + 'deg');
$('#results').append('<p>Rotate: ' + angle + 'deg</p>');
}
根据岗位,但是这作品,超过180度的值,我得到负数,并且360deg返回零。我需要能够正确地从180-360度返回度数值。
我是什么不对的代码,不会让它超过180度返回正确度的大转弯在做什么?
See the pen for a demo of this in action:如果您查看演示它将使很多更有意义。
找到了答案在另一个SO问题,你必须添加(2 * PI)如果结果弧度小于零。
这条线:
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
需要用这个来代替:
var radians = Math.atan2(b, a);
if ( radians < 0 ) {
radians += (2 * Math.PI);
}
var angle = Math.round( radians * (180/Math.PI));
我进来的时候需要这样的事情也是一样,决定从初始代码开始,做一个小的清理和一些小的改进;然后我修改为OP需要,所以我想现在在这里分享:
function getCurrentRotation(el){
var st = window.getComputedStyle(el, null);
var tm = st.getPropertyValue("-webkit-transform") ||
st.getPropertyValue("-moz-transform") ||
st.getPropertyValue("-ms-transform") ||
st.getPropertyValue("-o-transform") ||
st.getPropertyValue("transform") ||
"none";
if (tm != "none") {
var values = tm.split('(')[1].split(')')[0].split(',');
/*
a = values[0];
b = values[1];
angle = Math.round(Math.atan2(b,a) * (180/Math.PI));
*/
//return Math.round(Math.atan2(values[1],values[0]) * (180/Math.PI)); //this would return negative values the OP doesn't wants so it got commented and the next lines of code added
var angle = Math.round(Math.atan2(values[1],values[0]) * (180/Math.PI));
return (angle < 0 ? angle + 360 : angle); //adding 360 degrees here when angle < 0 is equivalent to adding (2 * Math.PI) radians before
}
return 0;
}
使用这样的:
getCurrentRotation(document.getElementById("el_id"));