单击按钮上的 cancelAnimationFrame 不起作用

cancelAnimationFrame on button click is not working

我正在尝试为单击按钮时向左或向右旋转设置动画。不幸的是,当我单击左旋转按钮时,它会自行编译,速度越来越快。右键单击也会发生同样的情况。需要多次点击相反的按钮才能取消旋转。

我想左键取消右旋转直接进入左旋转,反之亦然。现在,每次按下初始按钮时,您都必须单击相反的按钮时间。

代码如下:

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();
});

我认为最好将所有动画登录放入渲染循环和按钮事件中的控件。

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();

仅供参考

cancelAnimationFrame 的参数应该是 requestAnimationFrame 的 return 值。就像 setIntervalclearInterval.

var animId = requestAnimationFrame( anim );

//then
cancelAnimationFrame( animId );

它只是取消了下一个预定的功能。