Skip to content
Advertisement

How to add a Div on a Phaser Game

I have a game.js where all the sprites from my Phaser game is rendered. I also have a index.html that calls this script to render the game. I would like to add a <div> for a health bar over the game.js canvas but I am not able to do it, when I try, it only shows above or below the game.

Index.html:

<div id="game">

    <script src="/js/game.js"></script>
    <script src="/js/script2.js"></script>
    <script src="/js/script3.js"></script>
    <script src="/js/script4.js"></script>= 

    <div id="health-bar">the code of my health bar</div>    
</div>

game.js:

var game = new Phaser.Game( 3840, 2176, Phaser.CANVAS , 'game', { preload: preload, create: create, update: update, render:render}, false, true);

Advertisement

Answer

That’s because Phaser.Game is adding a new canvas child element to your <div id="game">, which you’ll see if you inspect the page.

A <canvas> is a block-level element, like a <div>, so the sibling elements will display one after the other.

If you want the div#health-bar to display above the canvas element you’ll need to position it accordingly. There’s multiple ways to do this, but one option might be adding the following CSS to your page, changing the top and left values as needed:

div#health-bar {
  position: absolute;
  z-index: 100;
  color: white;
  top: 50px;
  left: 100px;
}

If you do a search for CSS positioning you’ll find a plethora of resources on the topic, including this fairly good one from Learn CSS Layout.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement