Should I register a callback to handle the canvas blob object or does the CanvasRenderingContext2D.drawImage() blocking javascript execution until drawImage() is completed?
Yes CanvasRenderingContext2D.drawImage does run synchronously, but maybe not in the way you want...
If the sourceImage provided has not finished to fetch its resource (in case of HTMLImageElement or SVGImageElement) then, it will not wait for this.
var img = new Image();
img.src = "https://slowserv.er/bigImage.png";
ctx.drawImage(img, x, y); // here it won't wait for the image to be fetched
But if the image has been completely fetched, and its metadata has been parsed but the image data has not yet been decoded, then drawImage
will wait for it to be decoded. You can see a demo of this by running this Answer from Firefox.
This behavior seems to be catch-able only in Firefox, since Chrome will actually wait for the image to be decoded before firing the onload event.
So to answer your question, if the sourceImage is in a loaded status (e.g img.naturalWidth !== 0
for <img>
), then yes, you can be sure that drawImage will get executed before the next line of code is.
if(img.naturalWidth !==0) { // here we are sure our image is loaded
ctx.drawImage(img, x, y); // and here we are sure it has been drawn on the canvas
// even though toBlob is itself async
// this will pick the canvas has it is now
ctx.canvas.toBlob(onblobgenerated, options);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With