html2canvas 下载像桌面视图一样的图像,而不是 dom 内容的移动视图reactjs

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

在reactjs中,我使用

html2canvas
库来捕获屏幕并将其下载为图像。这是代码

const generateImage = async () => {
    const element = contentRef.current;
    const canvas = await html2canvas(element, { scale: 2 });
    const imgData = canvas.toDataURL('image/png');
    const imgBlob = await fetch(imgData).then(res => res.blob());
    const file = new File([imgBlob], 'document.png', { type: 'image/png' });

    const url = URL.createObjectURL(file);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'document.png';
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(url);
    return file;
  };

在移动视图上,它捕获移动视图的 html dom 内容,就像垂直长图像一样。在手机上我可以像桌面视图一样下载它吗?

reactjs html2canvas
1个回答
0
投票

改变视口对我有帮助

const generateImage = async () => {
    // Temporarily set the viewport to a larger size for capturing the content
    const originalViewport = document.querySelector('meta[name="viewport"]').getAttribute('content');
    const viewportMeta = document.querySelector('meta[name="viewport"]');
    viewportMeta.setAttribute('content', 'width=1440');
  
    // Wait for the viewport to adjust
    await new Promise(resolve => setTimeout(resolve, 300));
  
    const element = contentRef.current;
    const canvas = await html2canvas(element, { scale: 2 });
    const imgData = canvas.toDataURL('image/png');
    const imgBlob = await fetch(imgData).then(res => res.blob());
    const file = new File([imgBlob], 'document.png', { type: 'image/png' });
  
    // Restore the original viewport
    viewportMeta.setAttribute('content', originalViewport);
    // Wait for the viewport to adjust back
    await new Promise(resolve => setTimeout(resolve, 300));
    return file;
  };
© www.soinside.com 2019 - 2024. All rights reserved.