niklasvh / html2canvas

Screenshots with JavaScript
https://html2canvas.hertzen.com/
MIT License
30.42k stars 4.79k forks source link

Virtual DOM [DOMParser] Screenshot supported #2794

Closed rkbbd closed 2 years ago

rkbbd commented 2 years ago

Bug reports:

Taking a screenshot using Virtual DOM does not work. Error:

html2canvas.min.js:20 Uncaught (in promise) Error: Document is not attached to a Window
    at html2canvas.min.js:20:193237
    at html2canvas.min.js:20:1976
    at Object.next (html2canvas.min.js:20:2081)
    at html2canvas.min.js:20:1023
    at new Promise (<anonymous>)
    at a (html2canvas.min.js:20:774)
    at Vs (html2canvas.min.js:20:192912)
    at html2canvas.min.js:20:196186
    at takeScreenShot (set style [modal].html:94:7)
    at action (set style [modal].html:68:11)

Code:

 let htmlString = document.documentElement.innerHTML;
 let virtualDom = new DOMParser().parseFromString(htmlString, "text/html");
 html2canvas(virtualDom.body).then((canvas) => {
       let base64image = canvas.toDataURL("image/png");
      });

Specifications:

wuyuedefeng commented 2 years ago
async htmlTextToCanvas(htmlText) {
    const iframe = document.createElement('iframe');
    iframe.style.width = '0px'
    iframe.style.overflow = 'hidden'
    document.body.appendChild(iframe)
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write(htmlText)
    iframe.contentWindow.document.close()
    const dom = iframe.contentWindow.document.body

    //const dom = new DOMParser().parseFromString(`<div>111</div>`, "text/xml").firstChild
    const canvas = await html2canvas(dom).finally(() => {
      iframe.parentNode.removeChild(iframe)
    })
    return canvas
  }