html2canvas stops after rendering finishes

Viewed 642

I am trying to get a link of image generated by html2canvas like this:

App.js:

function capture() { 
  console.log('capture running')
  html2canvas(document.getElementById('leaderboard-div'), {
    letterRendering: 1, allowTaint: true, onrendered: function (canvas) {
      document.body.appendChild(canvas);
      console.log(canvas.toDataURL("image/jpeg"))   
    }
  }) 
} 

Leaderboard.html -

<body> 
  <script type="text/javascript" src="node_modules/html2canvas/dist/html2canvas.js"></script>
  <script src="./app.js"></script>       

  <div id="leaderboard-div" style="height: 450px; width: 750px; background-color: #202124; border-radius: 24px;">
    <div id="rank-1" style="background-color: #2d2e31; height: 140px; width: 100%;">
      <img id="rank-1-pic" class="top-rank-image" 
        src="someURL">
      <p id="rank-1-name" style="color: #ffffff; font-family: 'Courier New', Courier, monospace;">Name</p>
    </div>
  </div>
  <button id="btnCap" onclick="capture()">Test</button>

</body>

Here is what the console shows:

enter image description here

Nothing in the function(canvas) works.

I need to get that link in the console or in a variable so I can export the image somewhere...

1 Answers

I reckon I have found a solution to your problem. Looking at the code, it seems like you have followed an outdated tutorial which uses the old api. The onrendered does not work anymore. Nowadays the html2canvas uses a promise. Which basically means that you have to add a .then after html2canvas(document.getElementById('leaderboard-div'), { letterRendering: 1, allowTaint: true,}). Like so:

function capture() {
  console.log('capture running')
  html2canvas(document.getElementById('leaderboard-div'), {
    letterRendering: 1,
    allowTaint: true,
  }).then(canvas => {
    document.body.appendChild(canvas);
    console.log(canvas.toDataURL("image/jpeg"))
  });
}

Be careful however with cross origin images. That might give you an error like:

Unhandled Promise Rejection: SecurityError: The operation is insecure.

Or

file.html: Uncaught (in promise) DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

For more info on that see the github repo

Hope this helps! If not, please comment

Related