>我正在做一个动画课:
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.run
in 函数参数时,它只是传递一个回调函数,而不是this
引用。
在这种情况下,您必须bind
this
的引用
window.requestAnimationFrame(this.run.bind(this))
如果你不与this
绑定,那么在callback
,this
引用该回调函数(run()
(,而不是Animation
类。
有关详细信息,请参阅此参考如何绑定this
引用。