将类作为回调方法传递方法以请求动画帧

时间:2019-09-06 09:07:41

标签: javascript ecmascript-6

我正在上动画课:

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。

1 个答案:

答案 0 :(得分:0)

在函数参数中传递$scope.action = $routeParams.action; $scope.data = localStorageService.get("formatdata"); $scope.buttonName="Save"; ($scope.action == 'Edit' || $scope.action == 'Copy') ? $scope.buttonName="Update" : $scope.buttonName="Save"; 时,它只是传递了一个回调函数,但没有传递this.run引用。

在这种情况下,您必须this引用bind

this

如果不与window.requestAnimationFrame(this.run.bind(this)) 绑定,则在this内,callback引用该回调函数(this),而不是run()

有关更多信息,请参见此reference如何绑定Animation引用。

相关问题