2015-11-19 116 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