Search code examples
javascripthtmlcraftyjs

How do I contain my JavaScript game in a div?


In my HTML, I have a section in which I have JavaScript that adds an event listener which runs my game:

<div class="content">
<script>
        window.addEventListener('load', Game.start);
</script>
</div>

How do I make it so that the JavaScript is contained within the div above it? When it shows, the game is completely outside of it.

I'm using the crafty.js framework. Documentation here: http://craftyjs.com/api/


Solution

  • As mentioned in one of the comments, a div with the id "cr-stage" is important to crafty.js. However, you don't actually have to include it. If you leave it out, it will automatically be created.

    <html>
      <head>
        <!-- this is the crafty.js library, which you could load from another server -->
        <script src="crafty.js"></script>
    
        <!-- this is the script where all your game's JS goes -->
        <script src="mygame.js"></script>
    
        <script>
          window.addEventListener('load', Game.start);
        </script>
      </head>
      <body>
      </body>
    </html>
    

    If you use the above, you will get a cr-stage id created for you.

    Another thing that might be relevant to your question is if you want to center the cr-stage and remove a small gap that automatically appears above it. To do that, use this code:

    <html>
      <head>
        <!-- this is the crafty.js library, which you could load from another server -->
        <script src="crafty.js"></script>
    
        <!-- this is the script where all your game's JS goes -->
        <script src="mygame.js"></script>
    
        <script>
          window.addEventListener('load', Game.start);
        </script>
    
        <style type="text/css">
          /* remove the small gap at the top */
          body { margin-top: 0 }
    
          /* horizontally center your stage on the page */
          #cr-stage { margin: 0 auto 0 }
        </style>
      </head>
      <body>
      </body>
    </html>