1

I am trying to convert an image URL taken from firebase storage to a data URL. But when I opened the data URL, it displays a blank image in the new window. I need help to fix this issue.

var dataURL;
var imageurl;
var folder = formName + "/" + Insti + "/" + tenant + "/" + "Page 3";
var storageRef = firebase.storage().ref();
var listRef = storageRef.child(folder);

listRef.listAll()
  .then((res) => {
    res.items.forEach((itemRef) => {

      itemRef.getDownloadURL().then(function(imageurl) {

        console.log(imageurl)
        var img = new Image();
        var canvas = document.getElementById("image1");
        var ctx = canvas.getContext("2d");

        img.onload = function() {
          canvas.height = canvas.width * (img.height / img.width);

          var oc = document.createElement('canvas'),
            octx = oc.getContext('2d');
          oc.width = img.width * 0.5;
          oc.height = img.height * 0.5;
          octx.drawImage(img, 0, 0, oc.width, oc.height);
          octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
          ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,
            0, 0, canvas.width, canvas.height);

        };

        img.src = imageurl;
        dataURL = canvas.toDataURL("image/png");
        console.log(dataURL)

      });
    });
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });
<canvas width="300" height="200" id="image1"></canvas>
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
LQQ
  • 67
  • 6

1 Answers1

0

You invoke canvas.toDataURL() before the image is drawn to the canvas. So you export a blank canvas. Just move toDataURL inside the img.onload callback, that's it.

img.onload = function () {
    canvas.height = canvas.width * (img.height / img.width);

    var oc = document.createElement('canvas'),
        octx = oc.getContext('2d');
    oc.width = img.width * 0.5;
    oc.height = img.height * 0.5;
    octx.drawImage(img, 0, 0, oc.width, oc.height);
    octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
    ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,
        0, 0, canvas.width, canvas.height);

    dataURL = canvas.toDataURL("image/png"); // <-- Here
    console.log(dataURL);
};

img.src = imageurl;
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • I got this error: Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at Image.img.onload – LQQ Mar 08 '21 at 07:55
  • https://stackoverflow.com/questions/22710627/tainted-canvases-may-not-be-exported – Jeremy Thille Mar 08 '21 at 08:24