views:

47

answers:

2

So, I'm using whatever Object-Oriented options has to try and make a neat static image class so all I have to do is add said class to Canvas, and it will draw itself out! To test if everything worked, I added up some alerts. Now my Function starts spewing 'undefined' at the third alert.

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

so, that would be the class, and this is the bit of Javascript used on the HTML Page that keeps the Canvas. First it creates the image bla.jpg, and then it does the same, only with the class...

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();
A: 

I guess the problem here is that in

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

the scope of the function onload is the object stored in this.image. So the this within the function means the image itself. And the properties image, context, x and y are probably undefined for this class.

moxn
+2  A: 
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);
};
​

Note: it's also important to set the image src after you've set the onload handler, because if the image is in cache you may miss the event.

galambalazs