多次使用 html2canvas 时图像会被截断

问题描述 投票:0回答:1

我正在尝试使用 html2canvas 在我的 html 页面中创建一个 div 图像。当我第一次运行以下函数时,图像已正确保存。但是,如果我第二次单击按钮保存图像,则保存图像时,图像的底部和右侧会被切除,顶部和左侧会显示黑色背景。看起来它试图捕获的区域在第一次保存后就已经被偏移了。我已经确保单击按钮时没有向 div 添加填充或边距。

function captureAndSaveAsImage() {
    // Reset the window scroll position to the top
    window.scrollTo(0, 0);

    // Capture the content inside the 'matrixTableContainer' div
    html2canvas(document.getElementById('matrixTableContainer')).then(function (canvas) {
        // Convert the canvas to a data URL (JPEG or PNG)
        var imgData = canvas.toDataURL('image/jpeg');

        // Create a temporary anchor element
        var a = document.createElement('a');
        a.href = imgData;
        a.download = 'screenshot.jpg';

        // Trigger a click event on the anchor to initiate the download
        var clickEvent = new MouseEvent('click', {
            view: window,
            bubbles: true,
            cancelable: false
        });
        a.dispatchEvent(clickEvent);
    });
}

我还尝试在生成第一个图像后自动刷新页面。但是,用户正在填写表格,图像应该是其结果的屏幕截图。这意味着刷新页面时所有下拉菜单的结果都会丢失

javascript html html2canvas
1个回答
0
投票

如果您的 div“matrixTableContainer”包含多个 div,您可以编写一个循环或手动将所有 div 包含在文档中,然后下载该文档。

第 1 步:将 doc 声明为 'var doc= new jsPDF();' 步骤2:doc.addImage(imgData,15,20,90,imgHeight) 第 3 步:下载文档。

© www.soinside.com 2019 - 2024. All rights reserved.