javascript - 使用 html2canvas 将 HTML 表格转换为 Canvas

标签 javascript jquery html canvas

我正在尝试将 html 表格转换为 pdf。我试过使用 jspdf。它适用于 plain table 。但是当表格中有图像时不起作用。现在我正在尝试至少转换为 Canvas ,然后再转换为 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>

最佳答案

你的问题很简单,请补充

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: 是否允许跨域图片污染 Canvas

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

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

关于javascript - 使用 html2canvas 将 HTML 表格转换为 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093763/

相关文章:

javascript - 数据 双向切换文本

html - 如何从 SQL Server 中的字符串中去除 HTML 标签?

html - Internet Explorer 和 float : please explain

javascript - 无法通过类名使用 jquery 调用函数

javascript - .filter() 来自不同来源的相同数据

jquery - 我如何使用 jquery 显示和隐藏这个加载栏

jquery - woocommerce 变体 - 主题冲突问题

javascript - 在导出进行单元测试之前等待申请?

JavaScript : var 3po = true;?

html - 为什么 top 属性不适用于相对位置?