HTML5 Canvas: Get Event when drawing is finished

Solution 1:

Like almost all Javascript functions, drawImage is synchronous, i.e. it'll only return once it has actually done what it's supposed to do.

That said, what it's supposed to do, like most other DOM calls, is queue-up lists of things to be repainted next time the browser gets into the event loop.

There's no event you can specifically register to tell you when that is, since by the time any such event handler could be called, the repaint would have already happened.

Solution 2:

Jef Claes explains it pretty well on his website:

Browsers load images asynchronously while scripts are already being interpreted and executed. If the image isn't fully loaded the canvas fails to render it.

Luckily this isn't hard to resolve. We just have to wait to start drawing until we receive a callback from the image, notifying loading has completed.

<script type="text/javascript">        
window.addEventListener("load", draw, true);

function draw(){                                    
    var img = new Image();
    img.src = "http://3.bp.blogspot.com/_0sKGHtXHSes/TPt5KD-xQDI/AAAAAAAAA0s/udx3iWAzUeo/s1600/aspnethomepageplusdevtools.PNG";                
    img.onload = function(){
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');    

        context.drawImage(img, 0, 0);        
    };            
}                    

Solution 3:

You already have an event when the image loads, and you do one thing (draw). Why not do another and call the function that will do whatever it is you want done after drawImage? Literally just:

myImg.onload = function() {
    myContext.drawImage(containerImg, 0, 0, 300, 300);
    notify(); // guaranteed to be called after drawImage
};