我正在尝试构建一个 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 方法。