In the application I'm currently working on, I have 2 HTML5 Canvases that I'm using. One (TempCanvas) is for drawing charts temporarily and the other (MainCanvas) is for transferring the charts onto it for presentation. I have an image that I'm trying to draw onto TempCanvas, then when it's loaded I'd like to draw TempCanvas onto MainCanvas.
The issue that I'm running into is TempCanvas is being drawn onto MainCanvas before the image is drawn onto TempCanvas. Is there a way to wait until the image loads before continuing in the code?
My main function:
1 // Draw the chart onto the TempCanvas
2 $(this).DrawChart(TempCanvas, OtherParams);
3 // Draw the TempCanvas onto the MainCanvas
4 MainCanvasContext.drawImage(TempCanvas.get(0), PositionX, PositionY);
The DrawChart function:
1 $.fn.DrawChart = function(TempCanvas, OtherParams)
2 {
3 var image = new Image();
4 image.onload = function()
5 {
6 TempCanvasContext.drawImage(image, PositionX, PositionY);
7 // Draw some other stuff on the TempCanvas.
8 }
9 image.src = FilePath;
10 }
Basically I'm looking for a way to wait for DrawChart Line 6 to finish executing before Main Line 4 executes. Any pointers in the right direction would be greatly appreciated.
Use a callback inside your
otherParams
object like so:The DrawChart function:
Generally speaking, it is a good practice to create callback functions and or events when designing a jQuery plugin.. They are very useful and the entire library is built this way.
Note that you can do somthing like this:
And pass the entire handler as a parameter. It is your decision and should fit your needs. In your case probably better to leave it as it is.