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 '()'???

2

2 Answers 2

2

Try this:

window.onload = function(){
    window.$ = {
        ratio: 0.7,
        screen: 500,
        margin: 10,
        canvas: document.getElementById("canvas"),
        ctx: document.getElementById("canvas").getContext("2d"),
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.