0

(sorry for my english=/) I create an array when 'onload'.

(this:

var $ = {
    ratio: 0.7,
    screen: 500,
    margin: 10,
    canvas: document.getElementById("canvas"),
    ctx: document.getElementById("canvas").getContext("2d"),
}

and $.canvas and $.ctx is give 'null'. this work if i rewrite it

...
canvas: function(){return document.getElementById("canvas")}
...

but if i want to call this the variable looks like this $.canvas () how can i make this variable without '()'???

koopajah
  • 19,437
  • 8
  • 62
  • 93
Bendegúz
  • 748
  • 7
  • 15
  • 1
    appears that canvas is not loaded yet – karaxuna Feb 21 '13 at 17:23
  • 1
    possible duplicate of [Why does jQuery or a DOM method such as \`getElementById\` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Felix Kling Feb 21 '13 at 17:34

2 Answers2

2

Try this:

window.onload = function(){
    window.$ = {
        ratio: 0.7,
        screen: 500,
        margin: 10,
        canvas: document.getElementById("canvas"),
        ctx: document.getElementById("canvas").getContext("2d"),
    }
}
karaxuna
  • 25,822
  • 11
  • 76
  • 111
1

Looks like it's a problem with the scope of your $ variable. By declaring it with the var keyword inside the window.onload function, its scope is the local function and not the global scope.

You could define it outside of the onload function instead:

var $; // in the global scope

window.onload = function(){
    $ = {
        ratio: 0.7,
        screen: 500,
        margin: 10,
        canvas: document.getElementById("canvas"),
        ctx: document.getElementById("canvas").getContext("2d")
    };

    console.log($.canvas);
    console.log($.ctx);
};

By declaring it in the global scope, it can be accessed from outside of the onload function.

Fiddle

MrCode
  • 59,851
  • 9
  • 76
  • 106
  • 1
    I don't think it's a scope problem. OP says it works if he assigns a function to `$.canvas`. If it was a scope problem, then the error would be something like `Cannot read property 'canvas' of undefined`. – Felix Kling Feb 21 '13 at 17:35