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

标签 javascript oop canvas

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

相关文章:

javascript - 如何用react js实现分享到twitter

javascript - Angular 5-如何向构造函数添加多个参数?

javascript - svg 创建元素 3 秒直到 i 是 x

javascript - HTML5 Canvas - 绘制重叠的多边形

javascript - 如何在 Canvas 上制作文本渐变?

JavaScript 性能 : While vs For Loops

oop - 面试中用于编码测试的OOP问题

c - 如何将 C 宏/内联函数与变量函数名一起使用?

java - 为类外部的对象创建自定义方法

python - 在Python中使用OpenCV2去除接缝后,如何判断图像的大小?