所以,我有一个启动画面的构造函数。我正在使用画布图形(下面的 ctx 是对画布元素的 2d 上下文的引用),但是当我尝试获取上下文的本地副本时,我似乎丢失了它。有人知道为什么它在哪里变得不确定吗?(见下文)
function SplashScreen(_ctx)
{
this.loadScene = function()
{
this.img = new Image();
this.img.onload = this.render;
this.img.src = 'art/SplashScreen.png';
};
this.unloadScene = function()
{
delete this.img;
this.img = null;
CollectGarbage();
};
this.render = function()
{
alert(this.ctx);//<--------------undefined
alert(this.img);//<--------------undefined
this.ctx.drawImage(this.img,0,0);
};
alert(_ctx); //<--------------properly defined
this.ctx = _ctx;
alert(this.ctx);//<--------------properly defined
return this;
}
这里是我调用 SplashScreen 的地方(注意:下面来自 main.js,上面来自 splashscreen.js):
var ctx;
var scene_Splash;
var currentScene;
function main()
{
ctx = document.getElementById('canvas').getContext('2d');
alert(ctx); //<-------fine and defined
scene_Splash = new SplashScreen(ctx);
changeScene(scene_Splash, null, null);
}
function changeScene(_newScene, _transition, _time)
{
currentScene = _newScene;
currentScene.loadScene();
}
进一步扩展,这里是 index.html 文件中引用这些脚本的部分:
<html>
<head>
<script language="JavaScript" type="text/javascript" src="splashscreen.js"></script>
<script language="JavaScript" type="text/javascript" src="main.js"></script>
</head>
<body onload="main()">
<canvas id="canvas" width="640" height="960"></canvas>
</body>
</html>