Jump to content

How to scale an image to fit the window


gazpachu
 Share

Recommended Posts

I'm having a hard time trying to do something that should be quite straightforward, so I'm not sure what I'm missing.

How do we scale an image (to use as a game background) to fit the window?

This is my approach, which doesn't work:

preload() {
  this.load.image('bg', 'space3.png');
}

create() {
  const bg = this.add.image(0, 0, 'bg');

  bg.width = window.innerWidth;
  bg.height = window.innerHeight - this.parent.canvasOffset;

  // I would like to use this.game.width and this.game.height but those values don't exist
}

If I use bg.scaleX and bg.scaleY and set the values to 2.0, it does work, but what I want is to scale it to fit the window/viewport.

Link to comment
Share on other sites

Fixed with the following code:

config: {
        scene: {
          preload: this.preload,
          create: this.create,
          resize: this.resize,
        }
      }

window.addEventListener('resize', () => {
      this.game.resize(window.innerWidth, window.innerHeight);
    }, false);

create() {
  this.events.on('resize', this.parent.resize, this);
  this.bg = this.add.sprite(this.parent.game.config.width / 2, this.parent.game.config.height / 2, 'bg');
    this.bg.setDisplaySize(this.parent.game.config.width, this.parent.game.config.height);
}

resize(width, height) {
    this.cameras.resize(width, height);
    this.bg.setDisplaySize(width, height);
    // this.logo.setPosition(width / 2, height / 2);
  }

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...