gpt4 book ai didi

javascript - 不知何故,我的类无法定义一些变量

转载 作者:行者123 更新时间:2023-12-02 20:35:17 26 4
gpt4 key购买 nike

所以,我正在使用任何面向对象的选项来尝试制作一个整洁的静态图像类,所以我所要做的就是将所述类添加到 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);
}
}

所以,这就是类,这是 HTML 页面上使用的 Javascript 代码,用于保存 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();

最佳答案

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 也很重要,因为如果图像在缓存中,您可能会错过该事件。

关于javascript - 不知何故,我的类无法定义一些变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3379869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com