1

我正在尝试构建一个 JavaScript 类,但我遇到了这一行的问题:
this.ctx.drawImage(img.src, 0, 0, img.width, img.height);

出现的错误消息是:Uncaught TypeError: Cannot call method 'drawImage' of undefined

function jraw(id){
    this.canvas = document.getElementById(id);
    this.ctx = this.canvas.getContext('2d');
    this.setImage = function(url){
        var img = new Image();
        img.src = url;
        img.onload = function(){
            this.ctx.drawImage(img.src, 0, 0, img.width, img.height);
        };
    };
}

然后我这样称呼它:

<script>
    var j = new jraw("canvas");
    j.setImage("/images/my_image.jpg");
</script>

我如何获得 onload 以访问该ctx属性?我做了一些测试,它在 setImage 方法中看到了 ctx 属性,但没有看到 onload 方法。

4

3 回答 3

2

这是一种选择:

function jraw(id){
    this.canvas = document.getElementById(id);
    this.ctx = this.canvas.getContext('2d');
    var that = this;
    this.setImage = function(url){
        var img = new Image();
        img.src = url;
        img.onload = function(){
            that.ctx.drawImage(img, 0, 0, img.width, img.height);
        };
   };
}

虽然不是最好的。

于 2013-04-23T00:32:07.627 回答
1

尝试

this.setImage = function(url){
    var that = this;
    var img = new Image();
    img.src = url;
    img.onload = function(){
        that.ctx.drawImage(img, 0, 0, img.width, img.height);
    };
};

.drawImage()的第一个参数也是图像对象,而不是url

演示:小提琴

于 2013-04-23T00:37:04.993 回答
0

我相信问题在于,这在您的 onload 函数中与在您的 setImage 方法中有所不同。当 this 与方法一起使用时,它将绑定到该函数/方法是其一部分的对象,当它是一个函数时,它将绑定到全局对象。

您需要将此设置为 onload 方法之外的变量,或从 onload 方法中访问全局对象(几乎总是窗口对象)。

于 2013-04-23T00:36:30.613 回答