如何使用JavaScript获取以度为单位的CSS变换旋转值

如何使用JavaScript获取以度为单位的CSS变换旋转值

问题描述:

我正在使用CSS-Tricks上的代码以使用JavaScript获取当前的旋转变换(在CSS中).

I'm using the code found at CSS-Tricks to get the current rotation transform (in CSS) with JavaScript.

JavaScript函数:

JavaScript function:

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度之间的度值.

According to the post, this works, however, for values over 180 degrees, I get negative numbers, and 360deg returns zero. I need to be able to correctly return the degree value from 180-360 degrees.

这段代码让我无法返回180度的正确角度是什么意思?

What am I doing wrong with this code that won't let it return the correct degree turn over 180 degrees?

如果您观看演示,这将更加有意义:请参阅笔以获取有关此示例的演示,动作.

It will make a lot more sense if you view the demo: See the pen for a demo of this in action.

在另一个SO问题中找到答案,如果以弧度表示的结果小于零,则必须添加(2 * PI).

Found the answer in another SO question, you have to add (2 * PI) if the result in radians is less than zero.

此行:

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));