Reputation: 2242
i want to draw multiple images on canvas (background, on background another image, and on that image again another image will come), but some times it load image and some times not, i used setTimeout for delay to drawImage and load but still, it doesnt work.
if(somecondition)
{
//background image is 70kb
//image on background is 65kb
img3.src = "Image path"; //images is almost 2kb
img4.src = "Image path"; //images is almost 2kb
img5.src = "Image path"; //images is almost 2kb
img6.src = "Image path"; //images is almost 2kb
setTimeout(function()
{
img3.onload = function()
{
context.drawImage(img3, 272, 139, 172, 31);
}
},1000);
console.log("Linesss2 > 4 "+lines2);
bottomY = 290+((lines1-5)*10);
middleHeight = bottomY - 170;
setTimeout(function()
{
img4.onload = function()
{
context.drawImage(img4, 272, 170, 172, middleHeight); ///272
}
img6.onload = function()
{
context.drawImage(img6, 272, bottomY, 172, 71);
}
},1000);
}
var metrics1 = context.measureText(canvasText1);
var testWidth1 = metrics1.width;
var metrics2 = context.measureText(canvasText2);
var testWidth2 = metrics2.width;
context.fillText(canvasText1, 169.5-(testWidth/2), y-20);
context.fillText(canvasText2, 169.5-(testWidth/2), y-20);
wrapTextForCanvas1(context, canvasText1, 50, 180);
wrapTextForCanvas2(context, canvasText2, 260, 180);
}
Upvotes: 1
Views: 683
Reputation: 13089
So, you don't want to run an arbitrary time-out, you want to to be notified when each image loads. That way you know for sure that they've all loaded before you get started trying to use them. Just set the onload callback of each image so that it increments a counter. When that counter reaches the number of images you have to load, they're all done and you can start using them.
I answered another question on this recently. See here for the modified code: http://jsfiddle.net/enhzflep/RLP5Y/
Or here for the question itself: Images from previous functions are not drawn in the background (Canvas)
Upvotes: 2