NamesJ
NamesJ

Reputation: 13

Global object declared in function not accessible by other functions

In this code window.onload is used to delay the execution of the script to prevent references to the canvas occurring before the canvas is loaded. Withing start() the code map.fillStyle="CCFFEE runs as expected. I did not use var when declaring the map variable so as to make global to be referenced by other functions such as draw() and start(). However, for some reason start() accepts the variable as is, and uses it as expected, drawing the rectangle (in this case the background) to the screen while draw() throws an error when trying to use the variable. Error: Uncaught ReferenceError: map is not defined. This also occurs in the update() function as well as in the global scope outside of any functions. This has been tested with console.log("Map: " + map);. I hope that was concise enough for you to help.

window.onload=function() {
    init();
}

var fps = 30;
var now;
var then = Date.now();
var interval = 1000/fps;
var delta;

function Player(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
}

function Collider(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
}

function init() {
    canvas = document.getElementById('map');
    map = canvas.getContext('2d');
    start();
}

function start() {
    //Player Object
    player1 = new Player(gameMap.w / 3, (gameMap.h / 7) * 5, 30, 30);

    //Player Collider Object
    p1Collider = new Collider(player1.x - 15, player1.y - 5, player1.w + 30, player1.h + 130);

    //fillStyle and fillRect work here
    map.fillStyle="#CCFFEE";
    map.fillRect(0, 0, 1280,800);
}

function update(){
    //Error happens here too
}

function draw() {
    requestAnimationFrame(draw);
    now = Date.now();
    delta = now - then

    if (delta > interval) {
        then = now - (delta % interval);
    }

    //Character Collider
    //fillStyle and fillRect do not work here
    //Throws error:  Uncaught ReferenceError: map is not defined
    map.fillStyle="#CCFFEE";
    map.fillRect(p1Collider.x, p1Collider.y, p1Collider.w, p1Collider.h);
}

update();
draw;

Upvotes: 0

Views: 138

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

I assume the list line is draw();.

You are seeing this error because you are calling update(); and draw() before init() is called and set map.

Solution: Ensure that update and draw are called after init has been called. For example, by placing the calls inside the load event handler.

Upvotes: 1

Related Questions