Add Bootstrap component to your HTML5 games powered by Phaser thanks to its DOM support

When you have to add input texts or GUI elements in your HTML5 game, you probably miss the simple, clean and flat elegance of most modern hybrid app frameworks like Bootstrap.

Bootstrap is the world’s most popular front-end open source toolkit, featuring a lot of prebuilt components like alerts, cards, dropdowns and so on.

So the main question is: why should you build your components with Phaser when you already have plenty of them?

We only have to find a way to include Bootstrap component in Phaser games, and this is possible thanks to Phaser DOM support.

From Wikipedia: The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an XML or HTML document as a tree structure wherein each node is an object representing a part of the document.

Long story short, we can import HTML elements and handle them like Phaser game objects. Does it sound interesting? Yes, because it is.

Look at the example:

Try to interact with it. The red dropdown is a Bootstrap component, whose input is managed by a Phaser event listener and whose movement is managed by a Phaser tween.

How is it possible? First, we have to import in our index page Bootstrap and jQuery libraries as if the page were just another page powered by Bootsrap.

Obviously, we also import Phaser.

<!DOCTYPE html>
<html>
	<head>
        <style type = "text/css">
            body{
                background: #000000;
                padding: 0px;
                margin: 0px;
            }
        </style>
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
        <script src = "phaser.min.js"></script>
        <script src = "game.js"></script>
    </head>
	<body>
        <div id = "thegame"></div>
	</body>
</html>

In a separate file, which I called bootstrap.html, we add the code to generate the dropdown, just following Bootstrap docs.

<div class="btn-group">
    <button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
        I am a Bootstrap Dropdown
    </button>
    <ul class="dropdown-menu">
        <li>
            <a class="dropdown-item" href="#" id = "up">Move up</a>
        </li>
        <li>
            <a class="dropdown-item" href="#" id = "right">Move right</a>
        </li>
        <li>
            <a class="dropdown-item" href="#" id = "down">Move down</a>
        </li>
        <li>
            <a class="dropdown-item" href="#" id = "left">Move left</a>
        </li>
        <li>
            <hr class="dropdown-divider">
        </li>
        <li>
            <a class="dropdown-item" href="#" id = "center">Move to center</a>
        </li>
    </ul>
</div>

Now, the magic: Phaser support to DOM elements, explained in the commented source code:

let game;

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

        // 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() {

        // 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");

        // 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 that’s it, so simple and effective. This allows us to give players a HTML5 game with modern UI. Download the source code of the entire project.

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