MD.*_*SAN 2 javascript html5-canvas html2canvas
我使用html2canvas将 html 转换为 png,出现以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
let htmlString = document.documentElement.innerHTML;
let virtualDom = new DOMParser().parseFromString(htmlString, "text/html");
html2canvas(virtualDom.body).then((canvas) => {
let base64image = canvas.toDataURL("image/png");
});
Run Code Online (Sandbox Code Playgroud)
如果我传递浏览器 DOM 就可以了,但由于某种原因我需要新的 DOM,这就是我使用DOMParser. 类似问题:链接
现在没有合适的方法可以做到这一点。html2canvas中继附加到 element 的 window 对象。因为 html2canvas 已经允许通过 options 对象传递与defaultView相关的选项,所以抛出错误的守卫看起来像一个 bug,因为它应该检查是否传递了所有必要的选项。所以最好在那里打开一个问题!
作为一种解决方法,如果您信任 HTML,您可以尝试使用隐藏iframe,但仍应将其放置到文档中
const html = "<div>Hello World!</div>";
const iframe = document.createElement("iframe");
document.body.appendChild(iframe); // still required
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
html2canvas(iframe.contentWindow.document.body);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1664 次 |
| 最近记录: |