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 co
Solution 1:
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;
functionRotate(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 rotationif (ang == 180) flag2 = true; // change direction if 180 deg is reachedif (flag2 == true && ang == 0) { // if we go backwards and have reached 0 resetclearInterval(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.
Solution 2:
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.
Post a Comment for "Clockwise And Then Anticlockwise Rotation In Javascript"