如何用JavaScript获得CSS变换旋转值

jje*_*ton 7 javascript css transform css3

我正在使用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>');
}
Run Code Online (Sandbox Code Playgroud)

根据这篇文章,这适用于超过180度的值,我得到负数,360deg返回零.我需要能够正确地返回180-360度的度数值.

这个代码不能让它返回正确度数超过180度,我做错了什么?

如果您查看演示,它会更有意义:请参阅笔,了解此操作的演示.

dan*_*tra 9

我也需要这样的东西,并决定从最初的代码开始,做一些清理和一些小的改进;然后我根据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;
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

getCurrentRotation(document.getElementById("el_id"));
Run Code Online (Sandbox Code Playgroud)


jje*_*ton 7

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

这一行:

var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
Run Code Online (Sandbox Code Playgroud)

需要替换为:

var radians = Math.atan2(b, a);
if ( radians < 0 ) {
  radians += (2 * Math.PI);
}
var angle = Math.round( radians * (180/Math.PI));
Run Code Online (Sandbox Code Playgroud)