Add Bootstrap component to your HTML5 games powered by Phaser thanks to its DOM support and properly scaling the component

An interesting Phaser feature that isn’t used as it deserves is DOM support.

I already published a post about adding a Bootstrap component to a Phaser game, and now that I am going to use some Bootstrap stuff on my Wordle prototype, I needed to improve the script a bit.

But first, the main question: why should you use some Bootstrap components on your HTML5 game?

Well, because they make a lot easier to add options and menus to some kind of games. You can code them on your own from scratch, but I am firmly against reinventing the wheel, and you should be against it too, especially if you are a small studio or a one-man studio.

Using Bootstrap, or any other JavaScript UI framewordk, you can create in a couple of lines a dropdown like this one:

The problem is Phaser games often feature a Scale Manager, and as long as the game resolution matches with screen resolution, as in the above example which is a 500×500 window (in iframe) hosting a 500×500 game.

Let’s see what happens when we host a full HD game in a very smaller window, like in this example:

The dropdown menu is just too small to be properly used.

This is quite an issue because we can’t know the resolution our game is going to be played.

And now… the magic! Look at this small game:

Then at this full HD game:

And lastly at this game built to perfectly fit in a 750×1334 iPhone screen:

All Bootstrap dropdowns render perfectly, no matter the game or window resolution. How could it be possible?

Thanks to these three lines added to the original example:

let game;

window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        backgroundColor: 0x444444,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: 'thegame',
            width: 750,
            height: 1334
        },

        // this is needed to work with DOM elements
        dom: {
            createContainer: true
        },
        scene: playGame
    }
    game = new Phaser.Game(gameConfig);
    window.focus();
}

class playGame extends Phaser.Scene {
    constructor() {
        super('PlayGame');
    }
    preload() {

        // this is how we load HTML content
        this.load.html('dropdown', 'bootstrap.html');
    }
    create() {

        // just a text to show the resolution
        this.add.text(0, 0, 'game: ' + game.config.width + 'x' + game.config.height + '\nwindow: ' + window.innerWidth + 'x' + window.innerHeight, {
            font: '32px arial' 
        })

        // a DOM elements is added pretty much like a sprite
        let dropdown = this.add.dom(game.config.width / 2, game.config.height / 2).createFromCache('dropdown');

        // set DOM element scale according to game / window width and height ratios
        let ratioX = game.config.width / window.innerWidth
        let ratioY = game.config.height / window.innerHeight
        dropdown.setScale(Math.max(ratioX, ratioY));

        // click listener
        dropdown.addListener('click');

        // on click callback function
        dropdown.on('click', function(e) {

            // different actions to do according to element 'id' property
            switch(e.target.id) {
                case 'up':
                this.tweens.add({
                    targets: dropdown,
                    x: game.config.width / 2,
                    y: 50,
                    duration: 200
                });
                    break;
                case 'right':
                    this.tweens.add({
                        targets: dropdown,
                        x: game.config.width - 150,
                        y: game.config.height / 2,
                        duration: 200
                    });
                    break;
                case 'down':
                    this.tweens.add({
                        targets: dropdown,
                        x: game.config.width / 2,
                        y: game.config.height - 50,
                        duration: 200
                    });
                    break;
                case 'left':
                    this.tweens.add({
                        targets: dropdown,
                        x: 150,
                        y: game.config.height / 2,
                        duration: 200
                    });
                    break;
                case 'center':
                    this.tweens.add({
                        targets: dropdown,
                        x: game.config.width / 2,
                        y: game.config.height / 2,
                        duration: 200
                    });
                    break;
            }

        }, this);
    }
}

And now we can finally use DOM elements in our Phaser games light-heartedly. Download the source code of the complete example.

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