【问题标题】:Taking a screenshot using Virtual DOM does not work使用 Virtual DOM 截屏不起作用
【发布时间】:2022-08-20 14:31:05
【问题描述】:

使用 Virtual DOM 截屏不起作用。

错误:

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)

代码:

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

规格:

  1. html2canvas 测试版本:html2canvas 1.4.0
  2. 浏览器和 版本:谷歌浏览器和版本 96.0.4664.110(官方构建) (64 位)

    任何想法?

    标签: html2canvas


    【解决方案1】:

    可以使用iframe

    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
      }
    

    参考:Link

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 2011-10-10
      相关资源
      最近更新 更多