【发布时间】:2013-11-03 15:31:20
【问题描述】:
我正在使用代码 found at CSS-Tricks 通过 JavaScript 获取当前的旋转变换(在 CSS 中)。
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 度的值,我得到负数,并且 360 度返回零。我需要能够正确返回 180-360 度的度数。
我做错了什么这段代码不能让它返回正确的角度翻转 180 度?
如果您查看演示会更有意义:See the pen for a demo of this in action。
【问题讨论】:
-
如果角度小于或= 0,你不能简单地将360添加到角度吗?
-
是的,刚刚用我更新的代码添加了答案。认为这与我缺乏几何知识有关。在这里找到帮助:stackoverflow.com/questions/10343448/…
标签: javascript css transform