Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically scale Phaser 3 game dynamically mid-execution

I am wondering if there is a way to develop my game with a set resolution such as:

width: 1000,
height: 600,

And then have either HTML or Phaser automatically scale the canvas element whenever the window size changes.

I have tried using this:

width: window.innerWidth / 2,
height: window.innerHeight / 2,

But this does not preserve the aspect ratio, doesn't scale sprites/images correctly, requires a page reload for adjustments and means I cannot use specific x/y coordinates.

I have looked into Phaser 3's Scale manager and Flex Boxes but they do not seem to change the canvas size.

like image 796
exciteabletom Avatar asked Oct 27 '25 08:10

exciteabletom


2 Answers

The easiest solution that I could find was the following:

  • First, add these CSS styling rules:
html, body {
  height: 100%;
}

body {
  margin: 0;
  padding: 0;
  background: #111;
  color: #eee;
  font: caption;
}

canvas {
  /* And see postBoot() in JS */
  width: 100%;
  height: 100%;
  object-fit: contain;
  /* <https://caniuse.com/#feat=object-fit> */
}

#version {
  position: absolute;
  left: 5px;
  top: 605px;
}
  • Second, add a callback function in the config object to override Phaser's default styles like so:
var config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  physics: {
    default: "arcade",
    arcade: {
      gravity: { y: 200 }
    }
  },
  scene: {
    preload: preload,
    create: create
  },
  callbacks: {
    postBoot: function (game) {
      // In v3.15, you have to override Phaser's default styles
      game.canvas.style.width = '100%';
      game.canvas.style.height = '100%';
    }
  }
};

I found the code sample here.

EDIT:

If you want the game to resize whenever the window is changed mid-execution, you can make a similar function in your update loop like so:

function update(){
    (function() {
        const gameId = document.getElementById("game"); // Target div that wraps the phaser game
        gameId.style.width = '100%'; // set width to 100%
        gameId.style.height = '100%'; // set height to 100%
    })(); // run function
}
like image 104
Manuel Abascal Avatar answered Oct 28 '25 21:10

Manuel Abascal


Try this: https://www.w3schools.com/cssref/css3_pr_mediaquery.asp

It allowes you to adjust you css to a viewport.

like image 42
SilkeNL Avatar answered Oct 28 '25 21:10

SilkeNL