简体   繁体   中英

clockwise and then anticlockwise rotation in javascript

I want to rotate a canvas element to first do animation of rotation in clockwise direction by 180 degree then do a reverse(anticlockwise) rotation of 180 degree.I have used this code but its not working as i want.

  function Rotate(arg) { rotateInterval = setInterval(function () { arg.save(); //saves the state of canvas arg.clearRect(0, 0, arg.canvas.width, arg.canvas.height); //clear the canvas arg.translate(arg.canvas.width / 2, arg.canvas.height / 2); //let's translate if (flag2 == false) arg.rotate(-(ang += 5) * Math.PI / 180); //increment the angle and rotate the image //arg.style.rotate(5); else { ang = 0; arg.rotate((ang += 5) * Math.PI / 180); } if (ang == 180) { if (flag2 == true) flag3 = true; else flag2 = true; } if (flag3 == true && ang == 180) { clearInterval(rotateInterval) flag2 = false; } // ctxOne.drawImage(bowl, -ctxOne.canvas.width / 2, -ctxOne.canvas.height / 2, ctxOne.canvas.width, ctxOne.canvas.height); //draw the image ;) arg.drawImage(bowl, -90, -90, 180, 180); arg.restore(); //restore the state of canvas }, 100); } 

Does rotate() rotate an element relative to its current transformation or is it an absolute rotation? Instead of doing

    (angle+=5)*Math.PI / 180

try

    5*Math.PI / 180

for your rotate argument. That way rotate will rotate it by an addition 5 degrees every time. And make it -5 when it's going backwards. I guess at that point you'd use a counter to determine if 180/5 steps have passed and make it time to go backwards.

You have introduced a flag3 but I think you don't need it. I assume that rotation starts with ang = 0 and flag2 shall tell the rotation direction: increment when false and decrement when true. But you always set ang = 0 when it is true. Your code should look like:

var rotateInterval, ang = 0, flag2 = false;

function Rotate(arg) {

rotateInterval = setInterval(function () {
    arg.save();
    arg.clearRect(0, 0, arg.canvas.width, arg.canvas.height);
    arg.translate(arg.canvas.width / 2, arg.canvas.height / 2);

    if (flag2 == false) ang += 5; // increment ang if flag2 == false ( = go forward)
    else ang -= 5; // otherwise decrement ang ( = go backwards)

    arg.rotate(ang * Math.PI / 180); // set the new ang to the rotation

    if (ang == 180) flag2 = true; // change direction if 180 deg is reached

    if (flag2 == true && ang == 0) { // if we go backwards and have reached 0 reset
        clearInterval(rotateInterval)
        flag2 = false;
    }

    arg.drawImage(bowl, -90, -90, 180, 180);
    arg.restore(); //restore the state of canvas
}, 100);

}

Now the angle starts with 0, goes stepwise up to 180, then stepwise back to 0, then stops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM