简体   繁体   中英

html2canvas giving blank images

I'm trying to use html2canvas to take a screenshot of certain components in my react app when I take a screenshot but no matter what I try the images keep turning out to be blank.

This is what the code inside the onClick listener for my screenshot button looks like.

            const help = document.querySelector("#help");
            html2canvas(help).then((canvas) => {
              console.log(help, canvas);
              const a = document.createElement("a");
              a.href = canvas.toDataURL("image/png");
              a.download = "help.png";
              a.click();
            });

This is what #help element contains.

      <ul id="help">
        <li>Lorem</li>
        <li>lorem</li>
        <li>lorem</li>
        <li>lorem</li>
      </ul>

The console.log statement shows that the correct element is selected in the querySelector. I've even tried changing around fields like allowTaint, backgroundColor, foreignObjectRendering, useCORS from what I saw on other answers on here but none of these seemed to work for me. Also tried if removing all my custom css might help but even then it wasn't working. Setting logging to true didn't give me any outputs either so I'm pretty much clueless as about where to proceed from here.

Try to use getElementById it will work.

const getPrint = () => {
    const input = document.getElementById('headerr');
    html2canvas(input).then((canvas) => {
        document.body.appendChild(canvas);
        var imgWidth = 210;
        var pageHeight = 295;
        var imgHeight = (canvas.height * imgWidth) / canvas.width;
        var heightLeft = imgHeight;
        const imgData = canvas.toDataURL('image/png');
        //window.open(imgData);
        const pdf = new jsPDF('p', 'mm');
        var position = -2;
        pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        /* add extra pages if the div size is larger than a a4 size */
        while (heightLeft >= 0) {
            position = heightLeft - imgHeight;
            pdf.addPage();
            pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;
        }
        pdf.save('file.pdf');
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM