Skip to content Skip to sidebar Skip to footer

How To Ensure Images All Loaded Before I Reference In My HTML Canvas

I want to draw some images in on a HTML canvas with context.drawImage(Im1 ,205,18,184,38); In order to make sure it loads I need to put in code like this but then I cannot draw t

Solution 1:

In javascript there is the body onload method. Just create an event handler for it and run your drawing code there. OnLoad is called after all of the page elements are loaded.

Of course, it would also require that you directly reference those images somewhere in the body of your html. If they aren't already there, you could easily create a hidden div to do the loading.


Solution 2:

You can load all your images using a fn like one defined below which calls draw fn when all the images are loaded...

function loadImages()
{
    var imgToLoad = 3, imgLoaded = 0;

    var onImgLoad = function()
    {
        imgLoaded++;
        if(imgLoaded == imgToLoad)
            drawFromLoadedImages();
    };

    Img1 = new Image();
    Img1.src = 'images/x.png';
    Img1.onload = onImgLoad;

    Img2 = new Image();
    Img2.src = 'images/y.png';
    Img2.onload = onImgLoad;

    Img3 = new Image();
    Img3.src = 'images/z.png';
    Img3.onload = onImgLoad;
}

The above fn ensures that all 3 images are loaded before calling the draw function on the images.

Very old Question but hope this technique helps to anyone else coming to this question


Post a Comment for "How To Ensure Images All Loaded Before I Reference In My HTML Canvas"