2016-05-09 2 views
1

Я работаю с холстом и пытаюсь создать конструкторную функцию «Компонент» для создания различных элементов. Идея состоит в том, что она должна иметь возможность заполнять созданный элемент не только каким-то цветом, но и фоновым изображением. Он отлично работает с заполнением элемента цветом, но он не может загрузить изображение. Ошибок в консоли нет. На экране ничего нет. Нужна помощь, пожалуйста. Весь код теперь так:Конструктор компонента холста со встроенным объектом изображения не показывает изображение

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

Смотрите здесь, как загрузить изображение, а затем нарисовать его на холсте: 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); 
    } 
} 
+0

Благодарим вас за„привязку“и полезные ссылки. –

+0

Рад, что я могу помочь! – 1cgonza

Смежные вопросы