1

所以,我有一个启动画面的构造函数。我正在使用画布图形(下面的 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>
4

4 回答 4

1

对我来说很好:

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('in render: ' + this.ctx);
    };

    alert(_ctx);    //<--------------properly defined
    this.ctx = _ctx;
    alert(this.ctx);//<--------------properly defined
    return this;
}

var c = new SplashScreen(1);
c.render(); // in render: 1

确保使用new关键字实例化对象。

于 2012-06-08T19:48:25.157 回答
1

尝试:

this.img.onload = this.render.bind(this);
于 2012-06-08T20:22:02.997 回答
0

当您将函数绑定到事件处理程序时,它会被调用,就好像它是您附加处理程序的元素的属性一样;该函数不知道它曾经是某个其他任意对象的属性。

解决此问题的常用方法是使用一个或多个闭包来捕获您希望在处理事件处理程序期间可用的变量的值。

根据规范,您应该能够使用 handleEvent 方法而不是函数传递对象。然后以预期的方式调用此方法,即函数作为对象的属性调用。我知道这目前适用于 Firefox,但我不知道它是否适用于其他浏览器。

于 2012-06-08T20:16:33.193 回答
0

Esailija 发现了一直困扰我的问题,其他人也指出了这一点,但这是第一个:

@Zahel 没有调用它,而是将其作为事件侦听器添加到图像的 onload 事件中。然后浏览器在加载图像时调用它,并将此设置为图像,该图像显然没有 .img 或 .ctx 属性。– 埃塞利亚

于 2012-06-08T20:39:24.447 回答