具有内置图像对象的Canvas组件构造函数不显示图像

时间:2016-05-09 10:12:23

标签: javascript canvas

我正在使用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);
    }
}

1 个答案:

答案 0 :(得分:1)

请参阅此处如何加载图像然后在画布上绘制它:https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Example_A_simple_line_graph

如果有兴趣,这里有一个很好的解释如何访问"这个"在回调中:How to access the correct `this` context inside a callback?

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

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