user3055135
user3055135

Reputation: 13

canvas and stage losing global scope in easel.js

Here's the code. At the top, you can see that canvas and stage are declared as global variables. Then the initializeCanvas() function runs on page load and assigns those variables and loads a background image.

Strangely, though, stage and canvas end up undefined.

Why? And what can I do about it?

Roger

var canvas, stage

function initializeCanvas() {
    canvas = document.getElementById("starCanvas")
    canvas.width = window.innerWidth
    canvas.height = 720

    stage = new createjs.Stage("starCanvas")

    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded
}

function handleBackgroundImage_Loaded(evt) {
    background.x = 0
    background.y = 0
    stage.addChildAt(background,0);
    stage.update()  
}   

alert(canvas)
alert(stage)

Upvotes: 0

Views: 288

Answers (2)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

make initializeCanvas, an immediately invoked function. also, always use console.log to output an object for inspection.

var canvas, stage;

(function initializeCanvas() {
    canvas = document.getElementById("starCanvas");
    canvas.width = window.innerWidth;
    canvas.height = 720;
    stage = new createjs.Stage("starCanvas");
    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded;
})();

function handleBackgroundImage_Loaded(evt) {
    background.x = 0;
    background.y = 0;
    stage.addChildAt(background, 0);
    stage.update();
}
console.log(canvas);
console.log(stage);
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<canvas id="starCanvas"></canvas>

Upvotes: 0

5ka
5ka

Reputation: 257

You forgot to call the function I guess. Somewhere paste:

initializeCanvas();

Upvotes: 1

Related Questions