1

I'm working with canvas and try to create a constructor function 'Component' to create various elements. The idea is that it has to have the ability to fill the created element not only with some color, but with the background image. It works fine with filling the element with color, but it can't load the image. No errors in console. It's just nothing on screen. Need some help, please. The whole code now is like this:

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 Answers1

1

See here how to load an image and then paint it on the canvas: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Example_A_simple_line_graph

If interested, here is a good explanation for how to access "this" inside the callback: How to access the correct `this` context inside a callback?

In your case it should look something like:

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);
  }
}
Community
  • 1
  • 1
1cgonza
  • 1,589
  • 10
  • 20