CSS3 animation on conversion: rotation. A way to get the current degree of a rotating element?

I am working on an html5 interface that uses drag and drop. While I drag the element, the target gets the css class, which makes it bidirectional rotation due to -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 take the current state of rotation.

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

So my question is: is there a way to get the current degree value of an element that rotates through the animation?

Thanks. Hendrick

+7
html5 css3 animation drag-and-drop transform
source share
2 answers

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 2-degree degrees of rotation (i.e. rotation around the Z axis).

+18
source share

window.getComputedStyle (element, null) ['- webkit-transform'] will return a string representing the current transformation matrix. You can calculate the degree of rotation from this line by first analyzing it and then applying a few mathematical calculations.

+4
source share

All Articles