当在对象的方法中调用时,cancelAnimationFrame()似乎不起作用。我尝试将this值绑定到回调函数(如MDN所示与setTimeout),但在使用cancelAnimationFrame()时收到了TypeError。然后,我尝试将this值设置为名为_this的局部变量,并再次调用cancelAnimationFrame()。那时候,我没有收到一个错误,但动画本身还在播放。我怎么取消动画?
我重新创造了下面的问题。如果打开控制台窗口,则会看到动画仍在运行。
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();
发布于 2016-02-12 16:22:52
好像你错过了两件事。首先,在调用this.animation = window.requestAnimationFrame(this.play.bind(this));时总是调用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);
}
};..。但关键是,在问题中描述的用例中,它是没有用的。
https://stackoverflow.com/questions/35367149
复制相似问题