简体   繁体   中英

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.

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM