所以,我正在使用任何面向对象的选项来尝试创建一个整洁的静态图像类,所以我所要做的就是将所述类添加到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();
答案 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可能是未定义的。