Search code examples
javascriptcanvas2d-games

Trying to put my js game into html file, won't use canvas area


Let me know if I should have done anything differently.

I have a JavaScript game and right now I have index.htm file with canvas text in it that calls the JavaScript file. I wanted to be able to take the code form the js file and actually put it into the htm file so it results in only 1 file eg .htm instead of 2 files eg .htm and .js

I have tried to no avail and followed this guide... http://www.tutorialspoint.com/javascript/javascript_placement.htm

And as it would need to action on load I am putting my js code within the BODY area.

I am sure it is my ignorance at fault here so hopefully this is a very easy basic question the expert js devs can help me with.

Thanks!

EDIT 1:

Here is what I tried...

</head>
<body>
<canvas id="screen" width="310" height="310"></canvas>
<script type="text/javascript">
<!--
;(function() {
  var Game = function(canvasId) {
    var canvas = document.getElementById(canvasId);
    var screen = canvas.getContext('2d');
    var gameSize = { x: canvas.width, y: canvas.height };

    this.bodies = createInvaders(this).concat(new Player(this, gameSize));

    var self = this;
    loadSound("shoot.wav",function(shootSound) {
      self.shootSound = shootSound;
      var tick = function() {
        self.update();
        self.draw(screen, gameSize);
        requestAnimationFrame(tick);
      };

and the bottom of it is the following:

  var loadSound = function(url, callback) {
    var loaded = function() {
    callback(sound);
    sound.removeEventListener('canplaythrough', loaded);
    };

    var sound = new Audio(url);
    sound.addEventListener('canplaythrough', loaded)
    sound.load();
  };

  window.onload = function() {
    new Game("screen");
  };
})(); 
//-->
</script>
</body>
</html>

EDIT2: You guys are great, thanks a bunch. It was even more stupid than you would believe - I forgot to include the shoot.wav file in the same directory as the .htm file!

I am not sure how SO works but I feel I should give the answer to the first person to suggest checking the debugger (unless I can upvote each of you that suggested it)

Also I am not sure about that rogue semi colon before the first function as I seem to be getting away with it as the game now runs.

Thanks again to all who responded to my idiotic mishap!


Solution

  • Rogue semi colon before the function in your script tag? Any debugging errors in the browser console?