2016-05-30 24 views
0


使用此代碼我嘗試在imageUpdated爲true時更新繪製圖像的畫布。
我使用時間標記,因此圖像未從瀏覽器緩存中加載。
但是,當我使用時間標籤畫布保持空白。 它沒有時間標籤。當image.src具有時間標記時更新畫布圖像

var imageUpdated = true; 
if(imageUpdated) 
{ 
    imageUpdated = false; 
    var heightImg = new Image; 
    heightImg.src = '/path/to/image.png?' + new Date().getTime().toString(); 
    this.canvas = $('<canvas />')[0]; 
    this.canvas.width = this.width; 
    this.canvas.height = this.height; 
    this.canvas.getContext('2d').drawImage(heightImg, 0, 0, this.width, this.height); 
} 
/*rest of event happens here*/ 

謝謝!

回答

1

可能是因爲您在加載之前繪製圖像。 我想這也是它沒有時間標記的原因,它已經在緩存中,所以可以立即繪製。

解決方案是在圖像加載後繪製。因此,在圖像上添加一個eventListener:

image.addEventListener('load', callback); 

在回調中,在畫布上繪製圖像。

例如:

// add eventlistener 
heightImg.addEventListener('load', function(e) { 
    var width = heightImg.width; 
    var height = heightImg.height; 

    var canvas = document.querySelector('canvas'); 
    canvas.width = width; 
    canvas.height = height; 

    canvas.getContext('2d').drawImage(heightImg, 0, 0, width, height); 
}); 

// trigger the loading 
heightImg.src = url + '?time=' + new Date().getTime().toString(); 

而一個Fiddle

+0

這並獲得成功,謝謝! –