2010-07-31 2 views
0

Итак, я использую любые объектно-ориентированные параметры, чтобы попытаться сделать аккуратный статический класс изображений, поэтому все, что мне нужно сделать, это добавить указанный класс в Canvas и он выберется! Чтобы проверить, все ли работает, я добавил несколько предупреждений. Теперь моя функция начинает извергать «неопределенный» при третьем оповещении.Почему-то мой класс не может определить некоторые переменные

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

так, что бы класс, и это немного JavaScript, используемые на HTML-странице, которая держит Canvas. Сначала он создает 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(); 

ответ

0

Я думаю, проблема в том, что в

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

, сфера применения функции onload - это объект, хранящийся в this.image. Таким образом, функция в функции означает само изображение. И свойства image, context, x и y, вероятно, не определены для этого класса.

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, потому что, если изображение находится в кэше, вы можете пропустить это событие.

Смежные вопросы