不知何故,我的班级没有设法定义一些变量

时间:2010-07-31 21:33:53

标签: javascript oop canvas

所以,我正在使用任何面向对象的选项来尝试创建一个整洁的静态图像类,所以我所要做的就是将所述类添加到Canvas中,它将自己绘制出来!为了测试一切是否有效,我添加了一些警报。现在我的函数开始在第三个警报处喷出'undefined'。

function StaticImage(imgsource, cancontext, ex, wy) {
    this.x = ex;
    this.y = wy;
    this.context = cancontext;
    alert("Image class instantiated! " + imgsource);
    this.draw = function () {
        this.image = new Image();
        this.image.src = imgsource;
        alert("Draw function called!");
        this.image.onload = function () {
            alert(this.image + " loaded! drawing on: " + this.context + " at: " + this.x + ":" + this.py);
        };
        this.cancontext.drawImage(this.image, this.x, this.y);
    }
}

所以,这将是类,这是保留Canvas的HTML页面上使用的Javascript。首先它创建了图像bla.jpg,然后它也是如此,只有类......

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var bla = new Image();
bla.src = "bla.jpg";
bla.onload = function () {
    context.drawImage(bla, 50, 50);
};
var lol = new StaticImage("bla.jpg", context, 200, 200);
lol.draw();

2 个答案:

答案 0 :(得分:2)

function StaticImage(src, context, x, y) {    
    this.x = x;
    this.y = y;
    this.context = context;

    // save reference to the instance
    var self = this; 

    // initialize the image at initialization 
    // time instead of at every draw
    self.image = new Image();
    self.image.onload = function() {
        // self will still refer to the current instance
        // whereas this would refer to self.image
        alert(self.image + " loaded! drawing on: " + self.context +
              " at: " + self.x + ":" + self.y);
    };
    self.image.src = src;

    alert("Image class instantiated! " + src);
}

// make draw function part of the prototype
// so as to have only 1 function in memory
StaticImage.prototype.draw = function() {
    alert("Draw function called!");
    this.context.drawImage(this.image, this.x, this.y);
};
​

注意:在设置onload处理程序之后设置图像src 也很重要,因为如果图像在缓存中,您可能会错过该事件。 < / p>

答案 1 :(得分:0)

我想这里的问题是

  this.image.onload = function() {
    alert(this.image + " loaded! drawing on: " + this.context + " at: " + this.x + ":" + this.py);
  }

函数onload的范围是this.image中存储的对象。因此函数中的this表示图像本身。对于这个类,属性image,context,x和y可能是未定义的。