CSS3 rotate transition does not take the shortest path

I want to use the css3 transition to smooth the movement of the compass using the back of the head. I calculated the required rotation as an angle from 0 to 359.

The problem is that when it should go from 359 to 0, it does not rotate 1 degree clockwise, but instead rotates 359 degrees counterclockwise.

Is there a way to tell css to always take the shortest path for rotation?

+4
source share
2 answers

Conversion does exactly what you say.

359deg 1deg. "rollover" 360deg 1deg, 361deg. , .

, :

var rot = 0;  // lets start at zero, you can apply whatever later

, :

rot = 359;
// note the extra brackets to ensure the expression is evaluated before
//   the string is assigned this is require in some browsers
element.style.transform = ("rotate( " + rot + "deg )");

, :

rot = 1;
element.style.transform = ("rotate( " + rot + "deg )");

. , , 360 0 , . , element.style.transform, rot, rot. , , :

var apparentRot = rot % 360;

, , , , , + 360:

if ( apparentRot < 0 ) { apparentRot += 360; } 

, ( 360 ) . , , 0-360deg, . , + 360 , :

var aR,          // what the current rotation appears to be (apparentRot shortened)
    nR,          // the new rotation desired (newRot)
    rot;         // what the current rotation is and thus the 'counter'

// there are two interesting events where you have to rotate through 0/360
//   the first is when the original rotation is less than 180 and the new one
//   is greater than 180deg larger, then we go through the apparent 0 to 359...
if ( aR < 180 && (nR > (aR + 180)) ) {
    // rotate back
    rot -= 360;
} 

//   the second case is when the original rotation is over 180deg and the new
//   rotation is less than 180deg smaller
if ( aR >= 180 && (nR <= (aR - 180)) ) {
    // rotate forward
    rot += 360;
}

, rot:

rot += (nR - aR); //  if the apparent rotation is bigger, then the difference is
                  //  'negatively' added to the counter, so the counter is
                  //  correctly kept, same for nR being larger, the difference is
                  //  added to the counter

:

var el, rot;

function rotateThis(element, nR) {
    var aR;
    rot = rot || 0; // if rot undefined or 0, make 0, else rot
    aR = rot % 360;
    if ( aR < 0 ) { aR += 360; }
    if ( aR < 180 && (nR > (aR + 180)) ) { rot -= 360; }
    if ( aR >= 180 && (nR <= (aR - 180)) ) { rot += 360; }
    rot += (nR - aR);
    element.style.transform = ("rotate( " + rot + "deg )");
}

// this is how to intialize  and apply 0
el = document.getElementById("elementYouWantToUse");
rotateThis(el, 0);

// now call function
rotateThis(el, 359);
rotateThis(el, 1);

, , 0-359 .

+13

, . -1deg 0deg , 359deg 0deg .

0

All Articles