Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建以图像为属性的javascript对象_Javascript_Image_Object_Onload - Fatal编程技术网

创建以图像为属性的javascript对象

创建以图像为属性的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.

我对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.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
。当与旧的
函数(){}
方法一起使用时,这是正确的。但当使用箭头功能时,这不适用。

当提出重复问题时,请投票关闭。