Search code examples
javascriptangularleaflethtml2canvas

Error: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported


I have a map that I want to export it as Png. I'm using leaflet for initializing map and Leaflet.BigImage and html2canvas for capturing the image. my problem is that sometimes it works and sometimes it doesn't.

I tried many ways. my server side Api has Access-Control-Allow-Origin and in my code I allowed CORS.

html2canvas(element, {
        useCORS: true,
        allowTaint: true,
      }).then(function (canvas) {
        canvas.toBlob(function (blob) { //----> Error here!
          var a = document.createElement("a");
          document.body.appendChild(a);
          a.style = "display: none";

          var url = window.URL.createObjectURL(blob);
          a.href = url;
          a.download = "Export-Map.png";
          a.click();
          window.URL.revokeObjectURL(url);
          controlPanel.innerHTML = label;
          span.disabled = false;
          isLock = false;
        });
      });

and i set img.crossOrigin="anonymous" for my Image. I don't know why sometimes it doesn't work. I tried every other ways that duplicate questions said.


Solution

  • the problem was I had 2 maps in different tabs and the other map was tainting the canvas somehow. I solved the problem by using *ngIf so only one map works at the time. before that I was using hidden.