There is a well known and easy way to draw a datauri into a canvas:
var img = new Image();
img.onload = function () {
context.drawImage(this, 0, 0, canvas.width, canvas.height);
}
img.src = "data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";
This way is async, my question is wether there is a way to do it async.
Modern browsers all load the img element asynchronously & new Image() creates an img element.
There's no synchronous way.
If you just want to be sure all images are loaded before beginning to use them then you can code an image preloader like this:
// image preloader--loads all images and then calls the start callback
// put the paths to your images in imageURLs[]
var imageURLs=[];
// push all your image urls!
imageURLs.push("image1.png");
imageURLs.push("data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM...");
// the loaded images will be placed in images[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
}
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