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)
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>