Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Error: Element is not attached to a Document

Am trying to convert div to image using html2canvas lib , but am keep getting that error

html2canvas.min.js:20 Uncaught (in promise) Error: Element is not attached to a Document
at html2canvas.min.js:20
at html2canvas.min.js:20
at Object.next (html2canvas.min.js:20)
at html2canvas.min.js:20
at new Promise (<anonymous>)
at a (html2canvas.min.js:20)
at Vs (html2canvas.min.js:20)
at html2canvas.min.js:20
at HTMLInputElement.<anonymous> (index4.html:18)
at HTMLInputElement.dispatch (jquery-2.2.4.min.js:3)

I not understand what's wrong with my code , when i run the code on jsfiddle it not give me any error when i run it on my local system it give me error.

code

<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" ></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> 
</head>

<body>
<div id="phone">45454565756677</div>    

<div id="out_image"></div>
    
 <input type="button" value="Data to Image" id="data_to_image_btn" >
  
  
  
<script>
    
    $(function() { 
    $("#data_to_image_btn").click(function() { 
        html2canvas($("#phone"), {  // no error with : document.getElementById( but nothing is rendered
            onrendered: function(canvas) {
                console.log('done ... ');
                $("#out_image").append(canvas);
            }
        });
    });
}); 
</script>  
</body>
</html>
like image 971
user889030 Avatar asked Feb 16 '26 15:02

user889030


1 Answers

Try this:

html2canvas($("#phone")[0]).then((canvas) => {
    console.log("done ... ");
    $("#out_image").append(canvas);
});

The two changes are: pass the first element of the jquery selection to html2canvas, rather than the selection itself. That gets rid of the error ... but for something to happen it seems that you need to treat the call as a Promise, rather than pass an onrendered callback (that's the second change)

like image 121
geofh Avatar answered Feb 18 '26 06:02

geofh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!