Javascript 取消对象方法内部的AnimationFrame不工作

Javascript 取消对象方法内部的AnimationFrame不工作,javascript,constructor,bind,requestanimationframe,cancelanimationframe,Javascript,Constructor,Bind,Requestanimationframe,Cancelanimationframe,cancelAnimationFrame()在对象的方法中调用时似乎不起作用。我已尝试将此值绑定到回调函数(使用设置超时),但在使用取消动画帧()时收到类型错误。然后我尝试将this值设置为一个名为\u this的局部变量,并再次调用cancelAnimationFrame()。当时,我没有收到错误,但动画本身仍在播放。如何取消动画 我已经在下面重新创建了我的问题。如果打开控制台窗口,您将看到动画仍在运行 函数WhyWontItCancel(){ this.canvas=document.cr

cancelAnimationFrame()
在对象的方法中调用时似乎不起作用。我已尝试将
值绑定到回调函数(使用
设置超时
),但在使用
取消动画帧()
时收到类型错误。然后我尝试将
this
值设置为一个名为
\u this
的局部变量,并再次调用
cancelAnimationFrame()
。当时,我没有收到错误,但动画本身仍在播放。如何取消动画

我已经在下面重新创建了我的问题。如果打开控制台窗口,您将看到动画仍在运行

函数WhyWontItCancel(){
this.canvas=document.createElement(“canvas”);
this.canvas.width=200;
this.canvas.height=10;
document.body.appendChild(this.canvas);
this.draw=this.canvas.getContext(“2d”);
this.draw.fillStyle=“#f00”;
这个位置=0;
};
WhyWontItCancel.prototype.play=函数(){

如果(this.position似乎遗漏了两件事。首先,
this.animation=window.requestAnimationFrame(this.play.bind(this));
line总是在
play()时调用
被调用。与您可能认为的相反,
cancelAnimationFrame
只删除先前请求的RAF调用。严格来说,这里甚至不需要。其次,您不必绑定每个RAF调用;您可以只执行一次:

function AnimatedCanvas() {
  this.canvas = document.createElement("canvas");
  this.canvas.width = 200;
  this.canvas.height = 10;
  document.body.appendChild(this.canvas);
  this.draw = this.canvas.getContext("2d");
  this.draw.fillStyle = "#f00";
  this.position = 0;

  this.play = this.play.bind(this); // takes `play` from prototype object
};

AnimatedCanvas.prototype.play = function() {
  if (this.position <= 190) {
    this.draw.clearRect(0, 0, 400, 10);
    this.draw.fillRect(this.position, 0, 10, 10);
    this.position += 2;
    this.animationId = window.requestAnimationFrame(this.play);
  }
};
…但问题是,它在问题中描述的用例中没有用处

AnimatedCanvas.prototype.cancel = function() {
  if (this.animationId) {
    window.cancelAnimationFrame(this.animationId);
  }
};