首页 > 解决方案 > HTML2Canvas 适用于桌面,但不适用于移动设备。怎么修?

问题描述

该网站的重点是下载已签署同意书的图像。一切都可以在桌面上按我想要的方式运行,但不幸的是它在移动设备上不起作用。我尝试了 chrome、brave、firefox 和 safari。我要么显示图像但不下载,要么出现一些奇怪的页面失真。如何调整代码来修复它?

这是源代码: https ://github.com/jacelecomte/wwvhSigns

处理图像保存的方法在这里:

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

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

 injectScript('./src/html2canvas.js');
    injectHtml2canvas();
    finalizeScreenshot();

function saveScreenshot(canvas) {
    const fileName = "Consent Form";
    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();
    });
} 

//these 3 functions are run in a row to create and download the screenshot. 
 injectScript('./src/html2canvas.js');
 injectHtml2canvas();
 finalizeScreenshot();

标签: javascripthtmlhtml2canvas

解决方案


在调用 html2canvas 之前更改视口,然后再将其更改回来。这个答案来自github 上的 html2canvas 问题修复

这应该解决它:

1:给你的 <meta name="viewport"../> 一个 id,像这样:

<meta name="viewport" content="width=device-width, initial-scale=1.0" id="viewportMeta" />
  1. 修改功能

    function finalizeScreenshot() {
        var vp = document.getElementById("viewportMeta").getAttribute("content");
    
        document.getElementById("viewportMeta").setAttribute("content", "width=800");
    
        html2canvas(document.body).then(function (canvas) {        
            document.body.appendChild(canvas);
            saveScreenshot(canvas);
        }).then(function () {
            document.getElementById("viewportMeta").setAttribute("content", vp);
        }); }
    

推荐阅读