簡體   English   中英

使用 html2canvas 將 HTML 表格轉換為畫布

[英]Convert HTML table to canvas using html2canvas

我正在嘗試將 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>

ꜰɪʀꜱᴛ

您需要在選項中將useCORS屬性設置為true 這將加載圖像作為 CORS 服務。

查看可用選項

ꜱᴇᴄᴏɴᴅ

由於圖像的當前托管站點(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>

您的問題很簡單,請添加

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: 是否允許跨域圖片污染畫布

[更新] 作為@ℊααnd 更好的答案是使用您需要在選項中將useCORS屬性設置為true 這將加載圖像作為 CORS 服務。

檢查文檔https://html2canvas.hertzen.com/documentation.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM