Search code examples
javascriptfirefoxcanvasprogressive-web-appsonload

JavaScript img.onload() sometimes not firing (depending on device and file size)


I'm loading a picture from local storage and putting it to a blank canvas (size 300x150). The curious thing is, the code works well on Firefox Desktop, but fails for larger images on Firefox Android. I even tried with exactly the same pics - same result: no problem on PC, but canvas stays blank on Android. It seems that on the phone the onload()-Function is not firing if the file is larger than approx. 1.5 MB.

From the console output, it seems to me that it is writing the data to img.src correctly, but the img.onload() part seems not to fire at all.

What am I doing wrong? Thanks a lot in advance!

Here is the code:

 getImage(file) {

      let canvas = this.$refs.canvas;
      let context = canvas.getContext("2d");
      context.clearRect(0, 0, canvas.width, canvas.height);
      console.log(canvas.width); // 300
      console.log(canvas.height); // 150

      var reader = new FileReader();
      if (reader && file) {
        reader.readAsDataURL(file);

        reader.onload = (event) => {
          var img = new Image();
          console.log(img);
          img.onload = () => {
            console.log("starting img.onload"); // fires only for small pics on android, but PC is fine
            console.log(img.width); // 
            console.log(img.height);  // 

            if (canvas.width < img.width && canvas.height != 0) {
              canvas.height = (img.height * canvas.width) / img.width;
            }
            context.drawImage(img,0,0,img.width,img.height,0,0,canvas.width, canvas.height);
          };

          img.onerror = function() {
            console.log("Image failed!"); // never fired
          };

          img.src = event.target.result; // output seems correct
        };
      }
    },

Solution

  • thanks a lot for the comments, now I understood the problem and I used createObjectURL, which works perfectly. Thank you!!

    getImage(file) {
       let canvas = this.$refs.canvas;
       let context = canvas.getContext("2d");
       context.clearRect(0, 0, canvas.width, canvas.height);
       var url = URL.createObjectURL(file);
       var img = new Image();
       img.src = url;
       img.onload = () => {
          if (canvas.width < img.width && canvas.height != 0) {
             canvas.height = (img.height * canvas.width) / img.width;
          };
          context.drawImage(
             img,0,0,img.width,img.height,0,0,canvas.width,canvas.height
          );
       };
    }