Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

html - CSS3 animation on transform: rotate. Way to fetch current deg of the rotating element?

i am working on a html5 interface wich uses drag and drop. While i am dragging an element, the target gets a css-class, which makes it bidirectionally rotate due to a -webkit-animation.

@-webkit-keyframes pulse {
   0%   { -webkit-transform: rotate(0deg);  }
   25%  { -webkit-transform:rotate(-10deg); }
   75%  { -webkit-transform: rotate(10deg); }
   100% { -webkit-transform: rotate(0deg);  }
  }

.drag
{
    -webkit-animation-name: pulse;
    -webkit-animation-duration: 1s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: ease-in-out;
}

When I drop the target, I want it to adopt the current state of rotation.

My first thought was to check the css property with jquery and the .css('-webkit-transform') method. But this method just returns 'none'.

So my question: Is there a way to get the current degree value of an element which is rotated via animation?

Thanks so far Hendrik

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recently had to write a function that does exactly what you want! Feel free to use it:

// Parameter element should be a DOM Element object.
// Returns the rotation of the element in degrees.
function getRotationDegrees(element) {
    // get the computed style object for the element
    var style = window.getComputedStyle(element);
    // this string will be in the form 'matrix(a, b, c, d, tx, ty)'
    var transformString = style['-webkit-transform']
                       || style['-moz-transform']
                       || style['transform'] ;
    if (!transformString || transformString == 'none')
        return 0;
    var splits = transformString.split(',');
    // parse the string to get a and b
    var parenLoc = splits[0].indexOf('(');
    var a = parseFloat(splits[0].substr(parenLoc+1));
    var b = parseFloat(splits[1]);
    // doing atan2 on b, a will give you the angle in radians
    var rad = Math.atan2(b, a);
    var deg = 180 * rad / Math.PI;
    // instead of having values from -180 to 180, get 0 to 360
    if (deg < 0) deg += 360;
    return deg;
}

Hope this helps!

EDIT I updated the code to work with matrix3d strings, but it still only gives the 2d rotation degrees (ie. rotation around the Z axis).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...