簡體   English   中英

html2canvas - 錯誤:元素未附加到文檔

[英]html2canvas - error: Element is not attached to a Document

我有 2 個 function。

function test() {
    // Get the element.
    var element = document.getElementById('container');

    // Generate the PDF.
    html2pdf().from(element).set({
        margin: 1,
        foreignObjectRendering: true,
        filename: 'test.pdf',
        html2canvas: { scale: 2 },
        jsPDF: {orientation: 'portrait', unit: 'in', format: 'letter', compressPDF: true}
    }).save();
}

$(function() {
    $("#btnSave").click(function() {
        html2canvas($("#container"), {
            onrendered: function(canvas) {
                theCanvas = canvas;
                document.body.appendChild(canvas);

                // Convert and download as image
                Canvas2Image.saveAsPNG(canvas);
                $("#img-out").append(canvas);
                // Clean up
                //document.body.removeChild(canvas);
            }
        });
    });
});  

還有一個 div

<div id="container" style="width: 1000px; height: 500px; background-color: #1b5c72;">
    <div onclick="doSomething(event, this); changeColor(event, this)"  class="magnet" style="display: inline-block;">
        <object   class="123" style="pointer-events: none"  width="200"
                height="300"
                type="image/svg+xml"
                data="images/tiles/a4-vertical.svg">
        </object>
 </div>
    <div style="background-color: red; width: 100px; height: 100px;"></div>
</div>

我無法在第二個 function 中將 div 轉換為 canvas 並且無法在第一個 ZC1C4F125268EA763 中制作好 pdf。 不要出現在 canvas 和 pdf 中。 我只看到沒有 svg 的空主 div 和小紅色 div。
html2canvas 不能與<object>一起使用?

所以我不太熟悉 JQuery,因為我是 React 從站,但是當我在我的 React 應用程序中實現 html2canvas 時,我遇到了這個確切的錯誤。 我能夠通過 2 種方式修復此錯誤:

1:

const holder = document.createElement("div")
holder.innerHTML=<>My Content</>
//for the following code, you can append it anywhere then just delete it once you're done
document.body.appendChild(holder)
html2canvas(holder).then(canvas => {
    document.body.appendChild(canvas)
});

2:如果您想使用 querySelector 或其他需要已安裝組件的選擇器,則只需執行以下操作

<button onClick={()=>{
    const holder=document.querySelector(".my-class")

    //allowTaint:true saves images too
    html2canvas(holder,{allowTaint:true}).then(canvas => {
        document.body.appendChild(canvas)
    });
}}>HTML2Canvas</button>

暫無
暫無

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

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