How can I fix this error?
My code:
const wrapper = document.createElement("div");
const myHTMLString = "<div>Hello</div>";
wrapper.insertAdjacentHTML("afterbegin",myHTMLString);
//console.log(">>>",wrapper);
html2canvas(wrapper,{useCORS: true}).then((canvas) => {
wrapper.appendChild(canvas);
console.log("canvas>>",wrapper.appendChild(canvas));
var base64encodedstring = canvas.toDataURL('image/jpeg', 1.0);
console.log("base6", base64encodedstring );
});
Error:
176e275da87 1ms Starting document clone
Uncaught (in promise) Unable to find element in cloned iframe
How can I fix this error?
My code:
const wrapper = document.createElement("div");
const myHTMLString = "<div>Hello</div>";
wrapper.insertAdjacentHTML("afterbegin",myHTMLString);
//console.log(">>>",wrapper);
html2canvas(wrapper,{useCORS: true}).then((canvas) => {
wrapper.appendChild(canvas);
console.log("canvas>>",wrapper.appendChild(canvas));
var base64encodedstring = canvas.toDataURL('image/jpeg', 1.0);
console.log("base6", base64encodedstring );
});
Error:
Share Improve this question edited Jan 8, 2021 at 16:22 trincot 350k36 gold badges271 silver badges322 bronze badges asked Jan 8, 2021 at 15:52 Raana TashakoriRaana Tashakori 4572 gold badges8 silver badges19 bronze badges176e275da87 1ms Starting document clone
Uncaught (in promise) Unable to find element in cloned iframe
2 Answers
Reset to default 14The html2canvas documentation says (I highlight in bold):
The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM [...]
The script traverses through the DOM of the page it is loaded on. It gathers information on all the elements there, which it then uses to build a representation of the page. In other words, it does not actually take a screenshot of the page, but builds a representation of it based on the properties it reads from the DOM.
This all means that the argument you pass to html2canvas
must be an element that is present in the document. This explains the (uncaught) error you got:
Unable to find element in cloned iframe
Apparently this tool creates a temporary iframe
in which it clones the document. Then it will search the element you passed as argument. Since in your case wrapped
is not part of the document, this search fails.
So before calling html2canvas
you could do:
document.body.appendChild(wrapper);
And then if you don't want it to stay in the DOM, remove it again as soon as you have the canvas rendering.
I encounted the same problem. Finally I solved it like this:
html2canvas(targetElement, options);
->
html2canvas(targetElement.childNodes[0].children, options);
Just do not know why!!!