Talking about Game development, HTML5, Javascript and Phaser.
When it’s time to scale your HTML5 game to make it cover the largest area of the screen while keeping its width/height ratio and showing the entire game with no cropping, we all rely a bit too much on the framework we are using, because all the most important – linke Phaser or Construct – have their own scale manager doing the dirty work for us. What if we use a framework which does not support scale management – like Phaser 3, at the moment – or we build a HTML5 game on our own without using any framework? The creation of your little scale manager is very easy, and if you are a loyal reader you should already have noticed it in the creation of the Phaser 3 version of Sokoban. Anyway, let’s have a look at what we need. A CSS TO CENTER THE GAME The game should be centered in its container, this can be done by assigning a style to the canvas which will host the game.
canvas{
display:block;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
function resize() {
var canvas = document.querySelector("canvas");
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var windowRatio = windowWidth / windowHeight;
var gameRatio = game.config.width / game.config.height;
if(windowRatio < gameRatio){
canvas.style.width = windowWidth + "px";
canvas.style.height = (windowWidth / gameRatio) + "px";
}
else{
canvas.style.width = (windowHeight * gameRatio) + "px";
canvas.style.height = windowHeight + "px";
}
}
resize
function? At the beginning of the game and each time the window is resized.
In the Sokoban with Phaser 3 case, it will be:
window.onload = function(){
var gameConfig = {
type: Phaser.CANVAS,
width: gameOptions.gameWidth,
height: gameOptions.gameHeight,
scene: [playGame]
};
var game = new Phaser.Game(gameConfig);
resize();
window.addEventListener("resize", resize, false);
}
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.