javascriptcanvashtml5-canvasdom-eventsdrawimage

HTML5 Canvas: Get Event when drawing is finished


I'm drawing an image to a canvas element. I then have code that depends on this process to be finished. My code looks like this:

var myContext = myCanvasElement.getContext('2d'),
    myImg = new Image();

myImg.onload = function() {
    myContext.drawImage(containerImg, 0, 0, 300, 300);
};

myImg.src = "someImage.png";

So now, I would like to be notified when drawImage is done. I checked the spec but I couldn't find either an event or the possibility to pass a callback function. So far I just set a timeout, but this obviously is not very sustainable. How do you solve this problem?


Solution

  • 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.