创建以图像为属性的javascript对象
我对javascript比较陌生,以前只使用Python编程,用这种语言创建对象实例比较困难创建以图像为属性的javascript对象,javascript,image,object,onload,Javascript,Image,Object,Onload,我对javascript比较陌生,以前只使用Python编程,用这种语言创建对象实例比较困难 class SteeringWheel { constructor(id) { this.id = id; this.can = document.getElementById(this.id); this.ctx = this.can.getContext('2d'); this.img = new Image(); //some img this.
class SteeringWheel {
constructor(id) {
this.id = id;
this.can = document.getElementById(this.id);
this.ctx = this.can.getContext('2d');
this.img = new Image();
//some img
this.img.src = "https://images-na.ssl-images-amazon.com/images/I/41iNBF9Q%2BsL._SX425_.jpg";
this.img.onload = function() {
this.ctx.drawImage(this.img, 0, 0);
}
}
var st = new SteeringWheel('st1')
但出现以下错误:
Uncaught TypeError: Cannot read property 'drawImage' of undefined
我试图嵌套onload函数,但它不起作用
this.ctx.onload = function() {
this.img.onload = function() {
this.ctx.drawImage(this.img, 0, 0);
}
}
在my.html文件中有一个id为“st1”的画布。之后我调用上面写的脚本
我创建对象的原因是因为我未来的意图是调用:
var st = new SteeringWheel('st2')
var st = new SteeringWheel('st3')
并且具有同一对象的多个实例
这可能是一个愚蠢的问题,但我完全被阻止了 你能试试这个吗
this.img.onload = () => {
this.ctx.drawImage(this.img, 0, 0);
}
因为发生了
this
=this.img
。当与旧的函数(){}
方法一起使用时,这是正确的。但当使用箭头功能时,这不适用。当提出重复问题时,请投票关闭。