Monday, May 20, 2024
102
rated 0 times [  108] [ 6]  / answers: 1 / hits: 17559  / 11 Years ago, tue, march 19, 2013, 12:00:00

I am drawing on the canvas each time a user presses a button, however sometimes the image is not getting drawn on the canvas. I think this could be that the image isn't loaded in time before the context.drawimage function runs, as some of the smaller files sometimes get drawn. I've used the console and checked resources and so this is the only problem I can think of.



How do I 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);
}

More From » html5-canvas

 Answers
37

You should check if the image is loaded. If not then listen to the load 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, great source btw) suggests:



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 are not wanting to apply the stroke or fill. However, the idea is the same.


[#79487] Monday, March 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 2 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;