title: Typescript - Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
body: <p>I am building an Ionic App and I am getting this error when I try to convert to base64 an image from an URL.</p>
  
  <pre><code>Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
  </code></pre>
  
  <p>My code is the following:</p>
  
  <pre><code>public getBase64Image(imgUrl: string): Promise&lt;string&gt; {
      if (!imgUrl.includes("http")) {
        return;
      }
  
      return new Promise&lt;string&gt;(resolve =&gt; {
        let img = new Image();
  
        img.src = imgUrl;
        img.crossOrigin = "anonymous"
        img.onload = (() =&gt; {
          let canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height;
          let ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);
          let dataURL = canvas.toDataURL("image/png");
          resolve(dataURL);
        });
      });
    }
  </code></pre>
  
  <p>I've read other questions where setting <code>anonymous</code> in <code>crossOrigin</code> was the solution, but I already have it.</p>
  
  <p>Hope you can help me, thanks.</p>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>As a note, I don't get this the first time that I convert an image to base64 but I get it in the following times I try to edit an image.</p>