HTML5 / JS画布显示图片

时间:2015-11-19 19:01:22

标签: javascript html5 canvas

我在画布上显示图片时遇到问题,尤其是在使用Chrome时。

我有一个方法被调用来绘制一个肖像(名称,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();
};

1 个答案:

答案 0 :(得分: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);
        //...

    }
};