妙网科技 妙网科技 首页 妙网科技 网站开发 妙网科技 JS解析CSS的transform的scale和rotate

JS解析CSS的transform的scale和rotate

所属栏目: 网站开发 | 更新时间:2016-11-28 | 阅读:5119 次
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
#divTransform {
    margin: 30px;
    width: 200px;
    height: 100px;
    background-color: yellow;
    /* Rotate div */
    transform: rotate(9deg);
    -ms-transform: rotate(9deg);
    /* Internet Explorer */
    -moz-transform: rotate(9deg);
    /* Firefox */
    -webkit-transform: rotate(9deg);
    /* Safari 和 Chrome */
    -o-transform: rotate(9deg);
    /* Opera */
}
</style>

<body>
    <div id="divTransform">
    </div>
</body>
<script>
var el = document.getElementById("divTransform");
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].split(')')[0].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);

console.log('Scale: ' + scale);

// arc sin, convert from radians to degrees, round
var sin = b / scale;
// next line works for 30deg but not 130deg (returns 50);
// var angle = Math.round(Math.asin(sin) * (180/Math.PI));
var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));

console.log('Rotate: ' + angle + 'deg');
</script>

</html>