2013-03-19 144 views
4

每當用戶按下按鈕時,我都在畫布上繪製,但有時圖像沒有在畫布上繪製。我認爲這可能是圖像在context.drawimage函數運行之前沒有被加載,因爲有些小文件有時會被繪製。我已經使用了控制檯並檢查了資源,所以這是我能想到的唯一問題。HTML5畫布 - drawImage並不總是繪製圖像

如何避免此問題?

這是我的Javascript代碼。

var canvas = document.getElementById("myCanvas"); 
var context = canvas.getContext("2d"); 

var questionbg = new Image(); 
var answerbg = new Image(); 

//this code is inside a function that is called each time a user presses a button 
if(questiontype == "text"){ 
    questionbg.src = "./resources/textquestionbg.png"; 
    context.drawImage(questionbg, 0, 0); 
    } 
//if image question 
else if(questiontype == "image"){ 
questionbg.src = "./resources/imageaudiovideoquestionbg.png"; 
context.drawImage(questionbg, 0, 0); 
} 
//if audio question 
else if(questiontype == "audio"){ 
questionbg.src = "./resources/imageaudiovideoquestionbg.png"; 
context.drawImage(questionbg, 0, 0); 
} 
//else it is a video question 
else{ 
questionbg.src = "./resources/imageaudiovideoquestionbg.png"; 
context.drawImage(questionbg, 0, 0); 
} 

回答

11

您應該檢查圖像是否已加載。如果沒有,那麼聽取加載事件。

questionbg.src = "./resources/imageaudiovideoquestionbg.png"; 
if (questionbg.complete) { 
    context.drawImage(questionbg, 0, 0); 
} else { 
    questionbg.onload = function() { 
     context.drawImage(questionbg, 0, 0);  
    }; 
} 


MDN(Mozilla的文件,大源BTW)指出:

function draw() { 
    var ctx = document.getElementById('canvas').getContext('2d'); 
    var img = new Image(); 
    img.onload = function(){ 
    ctx.drawImage(img,0,0); 
    ctx.beginPath(); 
    ctx.moveTo(30,96); 
    ctx.lineTo(70,66); 
    ctx.lineTo(103,76); 
    ctx.lineTo(170,15); 
    ctx.stroke(); 
    }; 
    img.src = '/files/4531/backdrop.png'; 
} 

很顯然,你是不是想申請筆觸或填充。但是,這個想法是一樣的。

+0

太棒了,非常感謝喬! – user2177629 2013-03-19 16:05:47

+0

好抓...... – 2015-03-26 08:22:18

+1

最好在定義img.onload處理程序後設置img.src。 – Rantiev 2016-05-01 16:47:48