将带有类的方法作为请求动画帧的回调方法传递



>我正在做一个动画课:

class Animation{
constructor(id){
let canvas = document.getElementById(id);
this.frames = [];
this.step = 0;
this.ctx = canvas.getContext('2d');
this.img =  new Image();
Object.assign(canvas, bound);
this.img.src = "vessle.svg";
}
run() {
log('run')
log(this)
let frame = this.frames[this.step];
this.ctx.globalCompositeOperation = 'destination-over';
// clear canvas
this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight); 
//draw images
frame.forEach((pos)=>{
this.drawImage( pos)
})
window.requestAnimationFrame(this.run);
}
drawImage(pos){
//render stuff
}
}

当我在requestAnimationFrame中传递this.run时,似乎"this"中的其余值不包括在新上下文中。例如,当我第二次运行它时,没有定义this.frames。

当您传递this.runin 函数参数时,它只是传递一个回调函数,而不是this引用。

在这种情况下,您必须bindthis的引用

window.requestAnimationFrame(this.run.bind(this))

如果你不与this绑定,那么在callbackthis引用该回调函数(run()(,而不是Animation类。

有关详细信息,请参阅此参考如何绑定this引用。

最新更新