-1

I've searched for the answer to my question and haven't been able to find anything that really hits it, as far as I saw.

I have two chunks of Javascript here that I am using to create a simple 2d game in a web browser.

var myGamePiece;

var game = {

    canvas : document.getElementById("game-screen"),

    start : function(){
        this.context = this.canvas.getContext("2d");
    }
}

function startGame(){
    game.start();
}

And this one:

var myGamePiece;

var game = {

    start : function(){

        this.canvas = document.getElementById("game-screen");
        this.context = this.canvas.getContext("2d");

    }
}

function startGame(){
    game.start();
}

The first code snippet does not work. The canvas is NULL when I try to get the context. I'm wondering why? I realize why it works in the second one, well, I assume I do. It's beeing run in a function. Is the canvas attribute in the first one not being 'run' like it is in the second code snippet?

Comments and tips appreciated! :D

Brandon Vance
  • 33
  • 2
  • 7
  • You probably have the first script before the `game-screen` element in the HTML, so the element doesn't exist yet when the code runs. Put it at the bottom of the HTML and it will work. – Barmar Sep 12 '16 at 19:30
  • True. I have it in the so should I just link it in with later on in the html file? Where exactly should I put it then? – Brandon Vance Sep 13 '16 at 02:35
  • Either put it at the end of the body, or put your code in the `window.onload` function so it runs after the document is loaded. Aren't these solutions explained in the duplicate question I linked to? – Barmar Sep 13 '16 at 15:32
  • Well, I apologize for the duplicate question. I didn't know how to formulate the problem I was having into words. Thanks for the link, I'll look at that now. Cheers. – Brandon Vance Sep 15 '16 at 17:46
  • Don't worry about it. Questions like this come up multiple times every day. – Barmar Sep 15 '16 at 18:02

1 Answers1

0

Your first code calls document.getElementById("game-screen") immediately in the var game declaration.

That's probably running before the element exists.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896