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

A lot of people enjoyed my previous post to add Bootstrap component to your HTML5 games powered by Phaser thanks to its DOM support, but the DOM game object available on Phaser can be used with a lot more frameworks, like jQuery UI.

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. It was one of the first component libraries released, and features nice components like draggable elements.

So, here we go with a draggable jQuery UI element embedded in a Phaser project:

Drag the yellow element around the canvas.

The big issue with this script was the difference between page scale and canvas scale, due to Phaser scale manager.

I needed to add callbacks to draggable element and use some math to make page scale and Phaser scale compatible.

This is not an issue if you don’t scale your Project, but we all know most if not all HTML5 games do.

jQuery and jQuery UI are loaded in the HTML page:

<!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.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
		<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
		<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
		<script src = "phaser.min.js"></script>
        <script src = "game.js"></script>
    </head>
	<body>
        <div id = "thegame"></div>
	</body>
</html>

Then in another HTML file which I called jqueryui.html I added the draggable element mostly copying and pasting one of the official examples:

<div id = "draggable" class = "ui-widget-content" style = "cursor:pointer;padding:20px;background-color:yellow">
    <p>I am a jQuery UI draggable</p>
</div>

Finally, the Phaser script:

let game;

$(document).ready(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("draggable", "jqueryui.html");
    }
    create() {

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

        // game size / actual canvas size ratio
        let ratio = new Phaser.Math.Vector2(game.config.width / $("#thegame canvas").width(), game.config.height / $("#thegame canvas").height());

        // delta which is affected by the ratio
        let delta = new Phaser.Math.Vector2(0, 0);

        // turn "draggable" element into a draggable component
        $("#draggable").draggable({

            // drag callback: adjust element position according to delta and ratio
            drag: function(e, ui) {
                ui.position.left = (ui.position.left - delta.x) * ratio.x;
                ui.position.top = (ui.position.top - delta.y) * ratio.y;
            },

            // drag stop callback: update delta according to game/canvas ratio
            stop: function(e, ui) {
                delta.x = ui.position.left - ui.position.left / ratio.x;
                delta.y = ui.position.top - ui.position.top / ratio.x;
            }
      });
    }
}

Here is where I add the draggable element and handle the different page/canvas size ratio.

There’s nothing you can’t achieve with the power of Phaser, we already added Bootstrap and jQuery UI frameworks, do you have any other framework you would like to see working with Phaser?

Download the source code and enjoy.

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