【问题标题】:Convert HTML table to canvas using html2canvas使用 html2canvas 将 HTML 表格转换为画布
【发布时间】:2017-05-21 06:14:35
【问题描述】:

我正在尝试将 html 表格转换为 pdf。我尝试过使用 jspdf。它适用于普通桌子。但是当表格中有图像时不起作用。现在我正在尝试至少将其转换为画布,然后再转换为 pdf。但是当有图像时它也不起作用。

<html>
<head>
<style>
button{
    display:block;
    height:20px;
    margin-top:10px;
    margin-bottom:10px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js" ></script>
<script>
window.takeScreenShot = function() {
    html2canvas(document.getElementById("target"), {
        onrendered: function (canvas) {
            document.body.appendChild(canvas);
        },
        width:320,
        height:220
    });
}
</script>
</head>
<body>
    <div id="target">
      <table>
      <tr><td> <img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com"> </td>
      <td>saf</td></tr>
      <tr><td>saff</td>
      <td>wdqwewe</td></tr>
      </table>
    </div>

    <button onclick="takeScreenShot()">to image</button>
<body>
</html>

【问题讨论】:

标签: javascript jquery html canvas


【解决方案1】:

ꜰɪʀꜱᴛ

您需要在选项中将useCORS 属性设置为true。这将加载作为 CORS 服务的图像。

available options

ꜱᴇᴄᴏɴᴅ

由于图像的当前托管站点 (w3schools.com) 不支持 CORS,因此您必须将图像托管在本地服务器或支持跨平台的站点上来源资源共享       (即imgur.com)

这是一个工作示例...

var takeScreenShot = function() {
   html2canvas(document.getElementById("target"), {
      useCORS: true,
      onrendered: function(canvas) {
         document.body.appendChild(canvas);
      },
      width: 320,
      height: 220
   });
}
button {
   display: block;
   height: 20 px;
   margin - top: 10 px;
   margin - bottom: 10 px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div id="target">
    <table>
        <tr>
            <td> <img src="https://i.imgur.com/WamrIt4.jpg" alt="W3Schools.com"> </td>
            <td>saf</td>
        </tr>
        <tr>
            <td>saff</td>
            <td>wdqwewe</td>
        </tr>
    </table>
</div>
<button onclick="takeScreenShot()">to image</button>

【讨论】:

  • @techhunter 其他答案对您有何帮助?那应该行不通。这是正确的答案。
  • 感谢您的回复。两者都在工作。但我接受以上这对我来说很简单。所以我要投票给你的答案。
【解决方案2】:

你的问题很简单,请补充

allowTaint:true,

像这样的选项

window.takeScreenShot = function() {
html2canvas(document.getElementById("target"), {
    onrendered: function (canvas) {
        document.body.appendChild(canvas);

    },
    allowTaint:true,
    useCORS: true,
    width:320,
    height:220
});
}

它会解决你的问题

ps:allowTaint:是否允许跨域图片污染画布

[更新] 作为@ℊαα,更好的答案是使用 您需要在选项中将 useCORS 属性设置为 true。这将加载作为 CORS 服务的图像。

查看文档https://html2canvas.hertzen.com/documentation.html

【讨论】:

  • @ℊαα我在本地尝试了这段代码并且它工作我不知道为什么它在 jsfiddle 上不起作用无论如何我要投票给你并更新我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 2017-11-03
  • 2014-12-31
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多