【问题标题】:Uncaught (in promise) Unable to find element in cloned iframe #2460Uncaught (in promise) 无法在克隆的 iframe 中找到元素 #2460
【发布时间】:2021-04-14 08:27:12
【问题描述】:

我该如何解决这个错误?

我的代码:

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 );
});

错误:

176e275da87 1ms 开始文件克隆
Uncaught (in promise) 无法在克隆的 iframe 中找到元素

【问题讨论】:

    标签: javascript reactjs typescript html5-canvas html2canvas


    【解决方案1】:

    html2canvas documentation 说(我用粗体突出显示):

    该脚本允许您直接在用户浏览器上对网页或其部分进行“截图”。屏幕截图基于 DOM [...]

    脚本遍历加载它的页面的 DOM。它收集那里所有元素的信息,然后使用这些信息来构建页面的表示。换句话说,它实际上并没有截取页面的屏幕截图,而是根据它从 DOM 读取的属性构建它的表示形式。

    这一切都意味着您传递给html2canvas 的参数必须是文档中存在的元素。这解释了您遇到的(未捕获的)错误:

    无法在克隆的 iframe 中找到元素

    显然,这个工具会创建一个临时的iframe,它会在其中克隆文档。然后它将搜索您作为参数传递的元素。由于在您的情况下 wrapped 不是文档的一部分,因此此搜索失败。

    所以在致电html2canvas 之前,您可以这样做:

     document.body.appendChild(wrapper);
    

    然后,如果您不希望它留在 DOM 中,请在画布渲染完成后再次将其删除。

    【讨论】:

    • 非常感谢您的解释
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    相关资源
    最近更新 更多