簡體   English   中英

HTML5 / JS畫布顯示圖片

[英]HTML5/JS canvas displaying pictures

我在畫布上顯示圖片時遇到了麻煩,尤其是在使用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();
};

您正在傳遞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);
        //...

    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM