0

I'm working on an animation class:

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
    }

}

When I pass this.run in requestAnimationFrame, it seems like the rest of the values from "this" are not included in the new context. For example this.frames is not defined when I run it the second time around.

Himmators
  • 14,278
  • 36
  • 132
  • 223

1 Answers1

0

When you passing the this.run in function parameter, it is just passing a callback function but not with this reference.

In this scenario you have to bind the reference of this

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

If you don't bind with this then inside the callback, this refers to that callback function (run()), not the Animation class.

For more see this reference how to bind the this reference.

MH2K9
  • 11,951
  • 7
  • 32
  • 49