Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous way to put / transform base64 encoded data-uri to canvas

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.

like image 341
alexander farkas Avatar asked Jan 25 '26 04:01

alexander farkas


1 Answers

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[]

}
like image 190
markE Avatar answered Jan 27 '26 18:01

markE