Я работаю с холстом и пытаюсь создать конструкторную функцию «Компонент» для создания различных элементов. Идея состоит в том, что она должна иметь возможность заполнять созданный элемент не только каким-то цветом, но и фоновым изображением. Он отлично работает с заполнением элемента цветом, но он не может загрузить изображение. Ошибок в консоли нет. На экране ничего нет. Нужна помощь, пожалуйста. Весь код теперь так:Конструктор компонента холста со встроенным объектом изображения не показывает изображение
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);
}
}
Благодарим вас за„привязку“и полезные ссылки. –
Рад, что я могу помочь! – 1cgonza