【问题标题】:Download Image Using HTML2Canvas使用 HTML2Canvas 下载图像
【发布时间】:2019-11-13 14:34:35
【问题描述】:

我在下载网站图片时遇到问题。我正在使用来自:https://github.com/niklasvh/html2canvas 的 html2canvas 和标准 HTML、CSS 和 javascript 添加到网站。我尝试使用标准 HTML 代码进行下载( 链接文本),但它似乎不适用于我试图做的事情。我也尝试了这里的建议:https://ourcodeworld.com/articles/read/415/how-to-create-a-screenshot-of-your-website-with-javascript-using-html2canvas 以及其他一些网站,但我无法找到正确的代码来使其工作。 我可以使用以下代码将网页的图像附加到当前页面的末尾:

    html2canvas(document.body).then(function (canvas) {
    document.body.appendChild(canvas); });
}

如何编辑上述代码以下载网页而不是附加网页?

【问题讨论】:

    标签: javascript html html2canvas


    【解决方案1】:

    首先,将html2canvas库注入到网页中:

    function injectScript(uri) {
        const document = window.document;
        const script = document.createElement("script");
        script.setAttribute("src", uri);
        document.body.appendChild(script);
    }
    
    function injectHtml2canvas() {
        injectScript("//html2canvas.hertzen.com/dist/html2canvas.js");
    }
    
    injectHtml2canvas();
    

    脚本加载完成后,调用库函数保存截图:

    function saveScreenshot(canvas) {
        const fileName = "image";
        const link = document.createElement("a");
        link.download = fileName + ".png";
        console.log(canvas);
        canvas.toBlob(function (blob) {
            console.log(blob);
            link.href = URL.createObjectURL(blob);
            link.click();
        });
    }
    
    html2canvas(document.body, {
        allowTaint: true,
        useCORS: true
    }).then(saveScreenshot);
    

    另请参阅图片常见问题解答:

    为什么我的图片没有渲染?

    html2canvas 无法绕过浏览器设置的内容策略限制。绘制位于当前页面原点之外的图像会污染它们所绘制的画布。如果画布被污染,则无法再读取。因此,html2canvas 实现了在应用图像之前检查图像是否会污染画布的方法。如果您将allowTaint 选项设置为false,则不会绘制图像。

    如果您希望加载位于页面来源之外的图像,您可以使用代理来加载图像。

    http://html2canvas.hertzen.com/faq/

    【讨论】:

    • 这很有帮助。我不得不稍微调整几行并让它整体工作。谢谢。
    猜你喜欢
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多