0

I am a beginner to JavaScript, I already built a simply pygame with oo design and is translating it to JavaScript.

So in the main function, I am initializing a canvas in main,

let canvas = new Canvas();
canvas.render();

inside Canvas.js it is like this

    class Canvas{
    constructor()   {

        this.canvas = document.getElementById("main");

        this.ctx = this.canvas.getContext('2d');

        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;

        window.addEventListener('resize', function(){
            this.canvas.width = window.innerWidth;
            this.canvas.height = window.innerHeight;
        });
        this.img = new Image(); 
        this.img.src = './image/background.png';
        
        

        
    }

    render() {
        
        requestAnimationFrame(this.paint);
        
    }

    paint = () =>  {

        this.img.onload = () =>   {
            this.ctx.drawImage(this.img,this.canvas.width/2 - this.img.width/2 ,this.canvas.height/2 - this.img.height/2);
        }
        

        
    }

}

export {Canvas};

The resize function inside constructor is not working. I have searched but still can't find what's my problem. Thanks!

  • `this` in the event listener is the `window` object. You can use an arrow function if you don't want the `this` to change and still refer to your instance. – Kaiido May 29 '21 at 15:54
  • I am a bit confused, so I changed it to window.addEventListener('resize', () => { this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; }); But it is not working – Harder_Better May 29 '21 at 16:08
  • Yes sorry, you also have to handle the loding of your image differently. Here you are only adding a new load eventlistener to your image every frame. Instead the best would be to add it only once in the constructor and call the initial `render` from there. Alternatively, remove the load event completely and check if `this.img.complete` is `true` before calling drawImage. – Kaiido May 30 '21 at 01:09

0 Answers0