简体   繁体   English

html2canvas 在渲染完成后停止

[英]html2canvas stops after rendering finishes

I am trying to get a link of image generated by html2canvas like this:我正在尝试获取由html2canvas生成的图像链接,如下所示:

App.js:应用程序.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 -排行榜.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:这是控制台显示的内容:

在此处输入图像描述

Nothing in the function(canvas) works. function(canvas)中的任何内容都不起作用。

I need to get that link in the console or in a variable so I can export the image somewhere...我需要在控制台或变量中获取该链接,以便可以将图像导出到某处...

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.查看代码,您似乎遵循了使用旧 api 的过时教程。 The onrendered does not work anymore. onrendered不再起作用。 Nowadays the html2canvas uses a promise.现在html2canvas使用 promise。 Which basically means that you have to add a .then after html2canvas(document.getElementById('leaderboard-div'), { letterRendering: 1, allowTaint: true,}) .这基本上意味着您必须在.then html2canvas(document.getElementById('leaderboard-div'), { letterRendering: 1, allowTaint: true,})之后添加一个 .then 。 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.未处理的 Promise 拒绝:SecurityError:操作不安全。

Or或者

file.html: Uncaught (in promise) DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. file.html:未捕获(承诺)DOMException:无法在“HTMLCanvasElement”上执行“toDataURL”:可能无法导出受污染的画布。

For more info on that see the github repo有关这方面的更多信息,请参阅github 存储库

Hope this helps, If not, please comment希望对你有帮助,如果没有,请评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM