Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas to data url not working properly

I have a function that takes an img-element and returns a data url. This works like 7/10 times and returns a blank image 3/10 times. I view the created data url through my browser(chrome) and use the same images so I know that this function is returning broken images. Can anyone spot why?

function imgToDataURL(img) {
    var canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    var c = canvas.getContext('2d');
    c.drawImage(img, 0, 0);
    dataurl = canvas.toDataURL();
    return dataurl;
}

$(function() {
    img = new Image();
    img.crossOrigin = '';
    img.onload = function() {
        newimg = new Image();
        newimg.onload = function() {
            document.body.appendChild(newimg);
        }
        newimg.src = imgToDataURL(img);
    }
    img.src = 'https://somedomain.s3.amazonaws.com/someimg.png';
});

This example works most of the time but sometimes ends with a large white rectangle instead of the image.

like image 428
user2073343 Avatar asked Dec 02 '25 04:12

user2073343


1 Answers

You have to wait for images to load before drawing them using .drawImage function. Only after the image is loaded by the browser you can call your imgToDataURL function.

Something like this:

var image_sources = ["img1.png", "img2.png", "..."];

for(var i=0; i<image_sources.length; i++) {
    var new_img = document.createElement("img");
    new_img.onload = function() {
       imgToDataURL(this);
    };
    new_img.src = image_sources[i];
}
like image 168
letiagoalves Avatar answered Dec 04 '25 18:12

letiagoalves