JavaScript类未捕获类型错误

JavaScript类未捕获类型错误,javascript,onload,Javascript,Onload,我正在尝试构建一个JavaScript类,但这行代码有问题: this.ctx.drawImage(img.src,0,0,img.width,img.height) 显示的错误消息是:未捕获类型错误:无法调用未定义的方法“drawImage” function jraw(id){ this.canvas = document.getElementById(id); this.ctx = this.canvas.getContext('2d'); this.setImag

我正在尝试构建一个JavaScript类,但这行代码有问题:
this.ctx.drawImage(img.src,0,0,img.width,img.height)

显示的错误消息是:未捕获类型错误:无法调用未定义的方法“drawImage”

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>

var j=新的jraw(“画布”);
j、 setImage(“/images/my_image.jpg”);
如何获取onload以访问
ctx
属性?我做了一些测试,它在setImage方法中看到了ctx属性,但在onload方法中没有看到

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

虽然不是必需的,但它是最好的。

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

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

试试看

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);
    };
};
另外,第一个参数是图像对象,而不是
url


演示:

在哪一行,当地人当时的价值观是什么?与你所拥有的完全相同。你的意思是什么?此外,阿伦的回答做了几乎相同的事情,所以无论如何都是好的。