cancelAnimationFrame()
在对象的方法中调用时似乎不起作用。我已经尝试将this
值绑定到回调函数(如 MDN上所示setTimeout
),但在使用时收到了 TypeError cancelAnimationFrame()
。然后我尝试将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();