How to scale your HTML5 games if your framework does not feature a scale manager – or if you do not use any framework

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%);
}
Your declaration may vary according to the way you defined the canvas, the one I used is the most universal possible. A JAVASCRIPT TO RULE THEM ALL The above CSS just centers the canvas in the middle of the screen. The hardest part is to stretch it to make it fill the largest area of the screen while keeping its ratio. Look at this JavaScript function:
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";
    }
}
Let’s break it line by line: Line 2: selecting the canvas. This line may vary according to the structure of the page where the game is hosted, but you got the concept. Line 3: getting window width. In some cases you may need to get the parent element width Line 4: same concept with the window height. Line 5: determining window ratio. Line 6: determining game ratio. Line 7: now we have two cases: window ratio is greater then game ratio or game ratio is greater than window ratio. If game ratio and window ratio are the same, we do not need any adjustment so feel free to manage in one of the two cases decribed above. Line 8: window ratio is smaller than game ratio, so the new canvas width will be equal to window width. Line 9: adjusting canvas height according to window width and game ratio. Line 12: window ratio is greater than game ratio so the new canvas width will be determined according to window height and game ratio. Line 13: canvas height will be equal to window height. Ok, now, when to launch 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);
}
With this in mind, play Sokoban with Phaser 3 and see how the game scales to fit your window. Obviously there’s no need to reinvent the wheel if the framework already features a scale manager, just don’t get lost if you have to do it on your own.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers