首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对象方法内部的cancelAnimationFrame不工作

对象方法内部的cancelAnimationFrame不工作
EN

Stack Overflow用户
提问于 2016-02-12 16:10:38
回答 1查看 1.6K关注 0票数 1

当在对象的方法中调用时,cancelAnimationFrame()似乎不起作用。我尝试将this值绑定到回调函数(如MDN所示setTimeout),但在使用cancelAnimationFrame()时收到了TypeError。然后,我尝试将this值设置为名为_this的局部变量,并再次调用cancelAnimationFrame()。那时候,我没有收到一个错误,但动画本身还在播放。我怎么取消动画?

我重新创造了下面的问题。如果打开控制台窗口,则会看到动画仍在运行。

代码语言:javascript
复制
function 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";
  this.position = 0;
};

WhyWontItCancel.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;
  } else {
    //window.cancelAnimationFrame(this.animation.bind(this));
    var _this = this;
    window.cancelAnimationFrame(_this.animation);
    console.log("still running");
  }

  this.animation = window.requestAnimationFrame(this.play.bind(this));
};

var animation = new WhyWontItCancel();
animation.play();

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-12 16:22:52

好像你错过了两件事。首先,在调用this.animation = window.requestAnimationFrame(this.play.bind(this));时总是调用play()行。与您可能认为的相反,cancelAnimationFrame只删除先前请求的RAF调用。严格地说,这在这里甚至没有必要。第二,不必绑定每个RAF调用;您可以只执行一次:

代码语言:javascript
复制
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);
  }
};

您可能需要将“取消”添加到原型中,以便能够停止动画,例如:

代码语言:javascript
复制
AnimatedCanvas.prototype.cancel = function() {
  if (this.animationId) {
    window.cancelAnimationFrame(this.animationId);
  }
};

..。但关键是,在问题中描述的用例中,它是没有用的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35367149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档