按钮单击时,cancelAnimationFrame不起作用

时间:2016-05-10 15:26:24

标签: loops animation three.js rotation requestanimationframe

我试图在按钮点击时动画左或右旋转。不幸的是,当我单击左旋转按钮时,它会自动编译,变得越来越快。右键单击也会出现同样的情况。它需要多次点击相反的按钮来否定旋转。

我希望左按钮取消右旋转并直接向左旋转,反之亦然。现在,您必须在每次按下初始按钮时单击相反的按钮时间。

以下代码:

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

2 个答案:

答案 0 :(得分:1)

FYI

cancelAnimationFrame的arg应该是requestAnimationFrame的返回值。就像setIntervalclearInterval

var animId = requestAnimationFrame( anim );

//then
cancelAnimationFrame( animId );

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

答案 1 :(得分:0)

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

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();
相关问题