Javascript 带有内置图像对象的画布组件构造函数不';t显示';图像是什么

Javascript 带有内置图像对象的画布组件构造函数不';t显示';图像是什么,javascript,canvas,Javascript,Canvas,我正在使用canvas并尝试创建一个构造函数“Component”来创建各种元素。其思想是,它必须能够不仅用一些颜色,而且用背景图像填充创建的元素。它可以用颜色填充元素,但无法加载图像。控制台中没有错误。屏幕上什么都没有。需要帮忙吗。 现在整个代码如下所示: var myRect; function startGame (){ workingArea.create(); myRect = new Component(30, 30, "grass.jpg", 10, 120, '

我正在使用canvas并尝试创建一个构造函数“Component”来创建各种元素。其思想是,它必须能够不仅用一些颜色,而且用背景图像填充创建的元素。它可以用颜色填充元素,但无法加载图像。控制台中没有错误。屏幕上什么都没有。需要帮忙吗。 现在整个代码如下所示:

var myRect;

function startGame (){
    workingArea.create();
    myRect = new Component(30, 30, "grass.jpg", 10, 120, 'image');
}

var workingArea = {
    canvas: document.createElement('canvas'),
    create: function (){
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext('2d');
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    }
};


function Component(width, height, color, x, y, type){
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    this.type = type;
    if (this.type === 'image'){
        this.image = new Image();
        this.image.src = color;
    }
    var ctx = workingArea.context;
    if (type === 'image'){
        this.image.onload = ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
    }
    else{
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}
    }
    else{
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}

请参见此处如何加载图像,然后在画布上绘制:

如果您感兴趣,这里有一个很好的解释,说明如何在回调中访问“this”:

在您的情况下,它应该类似于:

function Component(width, height, color, x, y, type){
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.type = type;

  var ctx = workingArea.context;
  if (type === 'image') {
    this.image = new Image();
    // This is async, so you need to pass your drawImage inside a callback function
    this.image.onload = function() {
      ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
    }.bind(this); // Bind the "this" to the callback
    this.image.src = color; // This is valid, just unfortunate to name it color.
  } else {
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}

谢谢你的“绑定”和有用的链接。很高兴我能帮上忙!