Jon Snow
Jon Snow

Reputation: 3

cancelAnimationFrame on button click is not working

I am trying to animate a left or right rotation on button click. Unfortunately, when i click the button for left rotation, it compiles on itself, getting faster and faster. The same occurs with the right click. It takes multiple clicks of the opposing button to negate the rotation.

I would like the left button to cancel the right rotation and go straight into rotating left and vice versa. Right now, you have to click the opposing button time for each time you've pressed the initial button.

Code below:

var initialFrame = function () {
  requestAnimationFrame(initialFrame);
  renderer.render(scene, camera);
};   

var rotateLeft = function () {
  requestAnimationFrame(rotateLeft);
  wrap.rotation.y += -0.02;
  wrapBack.rotation.y += -0.02;
  renderer.render(scene, camera);
};

var rotateRight = function () {
  requestAnimationFrame(rotateRight);
  wrap.rotation.y += 0.02;
  wrapBack.rotation.y += 0.02;
  renderer.render(scene, camera);
};

initialFrame()

$("#left-button").click(function() {
  cancelAnimationFrame(rotateRight);
  rotateLeft();  
});

$("#right-button").click(function() {
  cancelAnimationFrame(rotateLeft); 
  rotateRight();
});

Upvotes: 0

Views: 303

Answers (2)

yomotsu
yomotsu

Reputation: 1462

FYI

The arg for cancelAnimationFrame supposed to be return value of requestAnimationFrame. Just like setInterval and clearInterval.

var animId = requestAnimationFrame( anim );

//then
cancelAnimationFrame( animId );

It just cancel next scheduled function.

Upvotes: 1

Davide Necchi
Davide Necchi

Reputation: 796

I think that it's better to put all the animation login into the render loop and the controls in the button event.

var step =0;
var initialFrame = function () {
  wrap.rotation.y += step;
  wrapBack.rotation.y += step;
  requestAnimationFrame(initialFrame);
  renderer.render(scene, camera);
  step=0; // if you want to rotate one step on a click (remove this for infinite rotation)
};   

var rotateLeft = function () {
  step=-0.02;
};

var rotateRight = function () {
  step=0.02;
};


$("#left-button").click(function() {
   rotateLeft();  
});

$("#right-button").click(function() {
   rotateRight();
});

initialFrame();

Upvotes: 0

Related Questions