How to resize a game screen when tab is inactive

Hello dear Phaser community! Please help me with my problem. I made a game that looks different in portrait and landscape orientation. And the game tries to fit to the canvas.

But when I switch to another browser tab and resize the browser window. My game doesn’t resize until I touch the window again.
I made a GIF with a representation
My config looks like this

let config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.FIT,
        width: 1280,
        height: 720,
    },
    scene: [BootScene, PreloadScene, EnterGameScreen, EndGameScreen, GameScene],
    backgroundColor: 0x484a77,
}

the resize function I call like this

window.onload = function() {
	window.focus();
    window.addEventListener("resize", resizeGame);
}

in a standalone browser, it doesn’t look like a big problem. But it happens when I rotate my mobile phone and switch between landscape and portrait, and it looks weird

What’s in resizeGame()?

in resizeGame () I check the window size and call a ‘resizeScreen()’ function in a scene.

function resizeGame() {
    let windowWidth = window.innerWidth;
    let windowHeight = window.innerHeight;
    
    if (windowWidth < windowHeight){
        let activeScenes = game.scene.getScenes({ active: true });
    
        activeScenes[0].resizeScreen(config.scale.width, config.scale.height);
    } else if (windowWidth > windowHeight){
        let activeScenes = game.scene.getScenes({ active: true });
        activeScenes[0].resizeScreen(config.scale.width, config.scale.height);
    }
};

function resizeScreen(width, height) {
    const screenWidth = width;
    const screenHeight = height;

    this.scale.setGameSize(screenWidth, screenHeight);
}

also, I put into ‘resizeScreen’ many ‘Object.assign’ functions which align UI elements depending on orientation. Like this

Object.assign(this.bestScoreTitle, {x: screenWidth / 2, y: screenHeight * 0.07});

I don’t think you need to call setGameSize() at all.

You can try

new Phaser.Game({
  // …
  callbacks: {
    postBoot: (game) => {
      const interval = setInterval(() => {
        if (game.scale.canvas) {
          console.debug('refresh');

          game.scale.refresh();
        } else {
          clearInterval(interval);
        }
      }, 1000);
    }
  }
});
1 Like

Thank you! It works!