Home > front end >  html2canvas failing to capture Google static map
html2canvas failing to capture Google static map

Time:10-30

I'm creating a booking reference for the user to download after successfully making a booking. It looks like this in the browser: enter image description here

However, after using html2canvas to get a screenshot of the component in React, I get this: enter image description here

I suspect the issue has to do with the fact that the static map's use is protected by an API key, causing issues to render the image in an external view.

This is the callback that fires on hitting the share button, which for now just downloads the png (which is then converted to pdf using jsPDF):

  const share = () => {
    const input = document.getElementById("trip-summary");
    if (input === null) return;
    html2canvas(input!).then((canvas) => {
      var image = canvas
        .toDataURL("image/png")
        .replace("image/png", "image/octet-stream"); 

        const pdf = new jsPDF();
        // @ts-ignore
        pdf.addImage(image, "PNG", 0, 0);
        pdf.save("download.pdf");
    });
  };

CodePudding user response:

It looks like an external source of content. You should set the allowTaint option to true.

html2canvas(input, { allowTaint: true }).then(...);

CodePudding user response:

Just wanted to add to the answer above.

It achieves exactly what I want, but you just need to set useCORS to true in the options as well

html2canvas(input!, { allowTaint: true, useCORS: true }).then(...)

, otherwise you'll get

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

  • Related