Html2Canvas images getting cropped

24 views Asked by At

I am using html2canvas for taking screenshots of the page. The images on the page are getting cropped. I have tried a lot of settings but nothing seems to fix this. Pasting my code below

// Function to load the html2canvas library
    function loadHtml2Canvas() {
        const script = document.createElement('script');
        script.src = 'https://html2canvas.hertzen.com/dist/html2canvas.min.js';
        document.head.appendChild(script);

        script.onload = () => {
            captureAndDownload();
        };
    }

    // Function to capture the DOM and download the image
    function captureAndDownload() {
        // eslint-disable-next-line no-undef
        window.scrollTo(0, 0);
        // eslint-disable-next-line no-undef
        html2canvas(document.body, {
            logging: true,
            useCORS: true,
            allowTaint: true,
            onclone: function() {
                console.log('args');
                console.log(arguments);
            }
        }).then(canvas => {
        // Convert canvas to data URL
            const dataUrl = canvas.toDataURL();

            // Create a temporary link element
            const link = document.createElement('a');
            link.href = dataUrl;
            link.download = 'captured_image.png'; // You can change the filename and format if needed

            // Append the link to the body and trigger the click event
            document.body.appendChild(link);
            link.click();

            // Remove the link from the DOM
            document.body.removeChild(link);
        });
    }

Also, I have noticed not all the images on the page get cropped some do and some don't, and also that too is very random ( sometimes one gets cropped and sometime some other one ).

Attaching images of the expected and actual parts of screenshot( Please ignore overlay on the required image)

Expected Image : Expected Image

Required Image : Required Image

Tried different configuration options but nothing helped.

0

There are 0 answers