HTML2Canvas在台式机上运行,​​但在移动设备上不行。怎么修?

时间:2019-12-23 06:12:31

标签: javascript html html2canvas

该网站的重点是下载已签署同意书的图像。一切都可以按照我在台式机上的方式工作,但不幸的是,它不适用于移动设备。我尝试了chrome,勇敢,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();

2 个答案:

答案 0 :(得分:1)

在调用html2canvas之前更改视口,然后再将其更改回。该答案来自html2canvas issue fix on github

这应该解决它:

1:给您的一个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);
        }); }
    

答案 1 :(得分:0)

您还应该能够设置自己的windowWidth设置,该设置应触发相关的媒体查询:

html2canvas( document.body, {
    windowWidth: '1280px'
} ).then( function( canvas ) {
    document.body.appendChild( canvas );
} );

请参阅可用的html2canvas options