使用 html2canvas 以固定宽度捕获页面,无论屏幕大小如何

Use html2canvas to capture a page at a fixed width no matter the screen size

我使用 html2canvas 将网页另存为图像,我希望在移动设备和 PC 上获得相同的结果。我的网页有一个 table,在较小的屏幕上呈现不同(通过 CSS)。我想 html2canvas 保存 canvas 就好像网页总是在 PC 屏幕上一样。这样网页上的 table 看起来总是一样的。

我目前有一个解决方法,可以在 html2canvas 运行之前临时将正文宽度和视口初始比例设置为更大的值,保存网页,然后恢复为之前的正文宽度和视口比例。我使用的代码在这个 post.

的底部

它大部分都有效,但用户体验很差,因为在 html2canvas 操作期间网页会变大,暂停一下(在保存期间)然后恢复。从用户的角度来看,这看起来不太好。此外,这并不总是适用于所有移动设备。

有更好的方法吗?我可以有某种屏幕外 html 镜像我的屏幕 html 但总是像在 PC 上一样呈现吗?

// adjust screen and viewport to allow all table elements to fit on the screen correctly
document.body.style.width = '1024px';
let viewport = document.querySelector("meta[name=viewport]");
let remembered_viewport = JSON.stringify(viewport.outerHTML)
viewport.setAttribute('content', 'width=device-width, initial-scale=2');

// use html2canvas to save the webpage
let tag = document.getElementById("all");
html2canvas(tag).then(function(canvas) {
    let link = document.createElement("a");
    link.download = filename.toLowerCase();
    canvas.toBlob( function(blob) {
            link.href = URL.createObjectURL(blob);
            link.click();
        }, 'image/jpg');
    });

// reset screen and viewport
document.body.style.width = "auto";
if (remembered_viewport.includes("initial-scale=0.5")) viewport.setAttribute('content', 'width=device-width, initial-scale=0.5');
if (remembered_viewport.includes("initial-scale=2")) viewport.setAttribute('content', 'width=device-width, initial-scale=2');
else viewport.setAttribute('content', 'width=device-width, initial-scale=1');

提前致谢,杰森。

感谢 CBroe,我确实使用屏幕外 iframe 让它工作。如下:

// capture my on screen html
let html = document.documentElement.outerHTML;
// create the iframe
// there is css to push it off screen (ie. left: -1024px;)
let iframe = document.createElement("iframe");
iframe.style.width = "1024px";
iframe.style.height = "100%";
document.body.appendChild(iframe);
// add html to iframe
iframe.srcdoc = html;

// wait for iframe to load
iframe.addEventListener("load", () => {
   // use html2canvas to save the webpage
   html2canvas(iframe.contentWindow.document.body).then(function(canvas) {
     let filename = "image.jpg";
     let link = document.createElement("a");
     link.download = filename.toLowerCase();
     canvas.toBlob( function(blob) {
            link.href = URL.createObjectURL(blob);
            link.click();
        }, 'image/jpg');
     });
});

我确实需要在加载 iframe 并保存图像后删除 iframe,但基本功能似乎可以正常工作,屏幕尺寸没有任何奇怪的变化。