2013-04-23 126 views
1

我试图建立一个JavaScript类,和我有这行的问题:
this.ctx.drawImage(img.src, 0, 0, img.width, img.height);JavaScript类遗漏的类型错误

,显示了该错误消息:遗漏的类型错误:无法调用“的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> 

如何获取onload以访问ctx属性?我做了一些测试,它看到setImage方法中的ctx属性,但不是onload方法。

回答

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

演示:给出`未捕获的类型错误Fiddle

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

虽然不是必需的最好的一个。

+0

:类型error' – 2013-04-23 00:34:38

+0

其上线,那个时候当地人的价值是什么? – 2013-04-23 00:37:25

+0

它与你所拥有的完全一样 – 2013-04-23 00:39:28

0

我相信问题是这是onload函数中的东西比你的setImage方法有所不同。当它与一个方法一起使用时,它将被绑定到函数/方法所属的对象,当它是一个被绑定到全局对象的函数时。

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

相关问题