reactjshtml2canvas

html2canvas download the image like desktop view instead of mobile view for dom content reactjs


In reactjs I am using html2canvas library to capture the screen and download it as an image. Here is the code

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

On mobile view it capture the html dom content as of mobile view like a vertically long image. Can on mobile i download it like a desktop view?


Solution

  • changing view port helped me

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