画布和舞台在easel.js中失去全球范围

时间:2017-04-01 15:42:59

标签: javascript canvas createjs easeljs

这是代码。在顶部,您可以看到canvas和stage被声明为全局变量。然后initializeCanvas()函数在页面加载时运行并分配这些变量并加载背景图像。

奇怪的是,舞台和画布最终未定义。

为什么呢?我能做些什么呢?

罗杰

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)

2 个答案:

答案 0 :(得分:1)

你忘了调用我猜的功能。 某处粘贴:

initializeCanvas();

答案 1 :(得分:0)

make initializeCanvas,一个立即调用的函数。另外,请始终使用console.log输出要检查的对象。



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>
&#13;
&#13;
&#13;