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