2015-11-19 112 views
0

我無法在畫布上顯示圖片,特別是在使用Chrome時。HTML5/JS畫布顯示圖片

我有一種方法被稱爲繪製肖像(名稱,img,邊框),但context.drawImage()似乎沒有在Chrome中工作。任何解決方案

Portrait.prototype.draw = function (context, x, y, tX, tY) { 
    context.save(); 
    context.translate(tX, tY);   
    context.fillStyle = 'blue'; 
    context.strokeStyle = 'black'; 
    context.strokeRect(x, y, 160, 200); 
    context.fillRect(x, y, 160, 200); 
    context.stroke(); 
    // adding the image 
    context.beginPath();   
    var img = new Image(); 
    var link = this.getImageUrl(); 
    img.src = link; 
    //context.drawImage(img,x+5,y+5); //works mozzila  
    img.onload = function() { context.drawImage(img,x+5,y+5); } 
    // partial work chrome but on refresh displays e.g two different portrait images in turn in a random portrait (if multiple portraits on canvas)   
    // text box 
    context.beginPath(); 
    context.fillStyle = '#ffffff'; 
    context.fillRect(x+5,y + 165,150,30); 
    // text 
    context.beginPath(); 
    context.fillStyle = 'black'; 
    var n = this.getName(); 
    context.font = "25px Aerial"; 
    context.fillText(n,x+5,y+190); // should give the name  
    context.restore(); 
}; 
+0

getImageURL()工作,它的一種方法,返回對象的正確url。 – Theepicpowner

回答

2

你傳遞img.onload將被異步執行,這意味着代碼的其他行,它的完成之前將進行的功能。將整個「繪製」包裝到image.onload函數中。

Portrait.prototype.draw = function (context, x, y, tX, tY) { 
    var img = new Image(); 
    var link = this.getImageUrl(); 
    img.src = link; 

    img.onload = function() { 
     context.save(); 
     context.translate(tX, tY);   
     context.fillStyle = 'blue'; 
     context.strokeStyle = 'black'; 
     context.strokeRect(x, y, 160, 200); 
     context.fillRect(x, y, 160, 200); 
     context.stroke(); 
     context.drawImage(img,x+5,y+5); 
     //... 

    } 
}; 
+0

你先生是救命恩人!我雖然可能是異步的,但我不知道如何解決它。謝謝。 – Theepicpowner

+0

哦,順便說一句,我不得不刪除var n = this.getName();因爲它不能引用正確的對象 – Theepicpowner

+0

您可以保留它,只需將'var self = this;'作爲繪圖函數的第一行並寫入'var n = self.getName()'! – Harangue