HTML5 canvas - drawImage does not always draw an image

I draw on the canvas every time the user clicks the button, however sometimes the image is not drawn on the canvas. I think it may be that the image does not load on time before the context.drawimage function is run, as sometimes some of the small files are drawn. I used the console and checked the resources, and so this is the only problem I can think of.

How to avoid this problem?

This is my Javascript code.

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); } 
+4
source share
1 answer

You should check if the image is uploaded. If not, then listen for the download event.

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


MDN (Mozilla Doc, an excellent source of btw) offers:
 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'; } 

Obviously, you do not want to apply a stroke or fill. However, the idea is the same.

+11
source

All Articles