Load Event on Image does NOT work in mobile browsers

707 views Asked by At

I have the following script (stripped down for this question) that uses the FileReader API to allow users to upload photos and display a thumbnail of their photo before they commit their changes.

        try {
        reader = new FileReader();
        reader.onload = (function (theImg) {
            return function (evt) {

                var img=new Image();
                img.src = evt.target.result;

                var canvas=document.createElement("canvas");
                var ctx=canvas.getContext("2d");
                var thumb_width = 200;
                var thumb_height = 150;

                img.onload = (function(){ 
                    var width = img.width;
                    var height = img.height;

                    if (width > height) {
                      if (width > thumb_width) {
                        height *= thumb_width / width;
                        width = thumb_width;
                      }
                    } else {
                      if (height > thumb_height) {
                        width *= thumb_height / height;
                        height = thumb_height;
                      }
                    }
                    canvas.width=width;
                    canvas.height=height;

                    ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

                    //alert(canvas.toDataURL().length);                 
                    theImg.src = canvas.toDataURL();                        

                });
            };
        }(source_img));

        reader.readAsDataURL(file);

    } catch (e) {

        alert("\nUnfortunately this method of uploading photos is not supported by this browser\n\nYou will be redirected to a standard Upload Form\n");

        return false;
    }

When testing this on Mac OS X (and Windows XP & 7) using Chrome, Safari and Opera works perfectly even without the img.onload = (function(){ }); but it was needed in Firefox because the source image was being assigned to an empty canvas, before the image had been loaded.

Great, so all working on desktops, until i tried testing this on my iPhone using Safari and Chrome. Since i cannot debug directly on my device, i managed to use the alert to show that sometimes the source image was being assigned to an empty canvas, which i thought would have been fixed by img.onload = (function(){ }); but apparently this does not work in mobile browsers unless something else is causing this to fail.

i have tried the following in place of img.onload = (function(){ });

$(img).load(function() { });

and even

img.addEventListener("load", function () { }, false);

If anyone has any ideas or suggestions, i would appreciate your help. Thanks.

0

There are 0 answers