2013-03-19 147 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