Question

This is the code i wrote to resize the image in aspect ratio, it works on chrome but not display on firefox, does anyone know what is wrong.

var image = new Image();

        image.src = data;

        //$(image).load(function () {

            var aspectRatio = getAspectRatio(parseFloat($(image).prop('naturalWidth')),
                              parseFloat($(image).prop('naturalHeight')),
                              dstWidth,
                              dstHeight);

            var canvas = document.createElement('canvas');
            canvas.width = dstWidth;
            canvas.height = dstHeight;

            var x = (dstWidth - aspectRatio[0]) / 2;
            var y = (dstHeight - aspectRatio[1]) / 2;
            var ctx = canvas.getContext("2d");
                ctx.drawImage(image, x, y, aspectRatio[0], aspectRatio[1]);

            return canvas.toDataURL("image/png");

This is work it generated by the canvas.toDataURL

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQEAAADACAYAAAAEL9ZYAAAA1klEQVR4nO3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwYD7QAB/UrDfgAAAABJRU5ErkJggg==

Was it helpful?

Solution

To make it work you will need to handle the asynchronous nature of image loading. You will have to use a callback mechanism here. The reason it "works" in Chrome is accident; that is the image happen to be in the cache when you try and/or the browser is able to deliver the uncompressed/decoded image before you use the image in the drawImage call.

This will probably not work when it's online for most users so to properly handle loading you can do -

Example:

function getImageUri(url, callback) {

    var image = new Image();
    image.onload = function () { // handle onload

        var image = this;  // make sure we using valid image

        var aspectRatio = getAspectRatio(parseFloat($(image).prop('naturalWidth')),
        parseFloat($(image).prop('naturalHeight')),
        dstWidth,
        dstHeight);

        var canvas = document.createElement('canvas');
        canvas.width = dstWidth;
        canvas.height = dstHeight;

        var x = (dstWidth - aspectRatio[0]) / 2;
        var y = (dstHeight - aspectRatio[1]) / 2;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(image, x, y, aspectRatio[0], aspectRatio[1]);

        // use callback to provide the finished data-uri
        callback(canvas.toDataURL());
    }
    image.src = url; // set src last
}

Then use it this way:

getImageUri(myURL, function (uri) {
    console.log(uri); // contains the image as data-uri
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top