Jace
Jace

Reputation: 85

HTML2Canvas works on desktop but not on mobile. How to fix?

The point of the website is to download an image of a signed consent form. Everything works how I would like on desktop, but it does not work on mobile unfortunately. I tried chrome, brave, firefox, and safari. I either get the image showing but not downloading, or some weird page distortion. How can I adjust the code to fix it?

this is the source code: https://github.com/jacelecomte/wwvhSigns

The methods that deal with the saving of the image are here:

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

Upvotes: 4

Views: 9000

Answers (2)

Howdy_McGee
Howdy_McGee

Reputation: 10663

You should also be able to set your own windowWidth setting which should trigger the relevant media queries:

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

See the available html2canvas options.

Upvotes: 1

Jonathan Harris
Jonathan Harris

Reputation: 433

Change the viewport just before calling html2canvas, then change it back afterwards. This answer was derived from html2canvas issue fix on github

This should fix it:

1: give your <meta name="viewport"../> an id, like this:

<meta name="viewport" content="width=device-width, initial-scale=1.0" id="viewportMeta" />
  1. revised function

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

Upvotes: 3

Related Questions