HTML2Canvas does not render full div, only what is visible on screen?

前端 未结 10 1748
甜味超标
甜味超标 2020-12-13 04:02

I\'m trying to use HTML2Canvas to render the contents of a div. Here is the code:

var htmlSource = $(\'#potenzial-page\')[0];

$(\'#btn\').on(\"click\", fun         


        
相关标签:
10条回答
  • 2020-12-13 04:22

    This is how I've achieved in Reactjs.

    Main problem were ratio and scale If you do a quick window.devicePixelRatio, it's default value is 2 which was causing the half image issue.

    const printDocument = () => {
      const input = document.getElementById('divToPrint');
      const divHeight = input.clientHeight
      const divWidth = input.clientWidth
      const ratio = divHeight / divWidth;
    
      html2canvas(input, { scale: '1' }).then((canvas) => {
        const imgData = canvas.toDataURL('image/jpeg');
        const pdfDOC = new jsPDF("l", "mm", "a0"); //  use a4 for smaller page
    
        const width = pdfDOC.internal.pageSize.getWidth();
        let height = pdfDOC.internal.pageSize.getHeight();
        height = ratio * width;
    
        pdfDOC.addImage(imgData, 'JPEG', 0, 0, width - 20, height - 10);
        pdfDOC.save('summary.pdf');   //Download the rendered PDF.
      });
    }
    
    0 讨论(0)
  • 2020-12-13 04:25

    I hope thet help you

    html2canvas(htmlSource, {scrollY: -window.scrollY}).then(function(canvas) {
                var img = canvas.toDataURL();
                window.open(img);
            });
    
    0 讨论(0)
  • 2020-12-13 04:25

    I used window.scrollTo()in my case and it worked for me.

    Below is a sample code

    $('#btn').on("click", function() { 
        window.scrollTo(0,0);     
        html2canvas(htmlSource).then(function(canvas) {
            var img = canvas.toDataURL();
            window.open(img);
        });
        window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
    });
    
    0 讨论(0)
  • 2020-12-13 04:25

    I just did something like this and it worked for me:

    html2canvas(document.querySelector("#capture2image"), {
                allowTaint: true,
                useCORS: true,
                logging: false,
                height: window.outerHeight + window.innerHeight,
                windowHeight: window.outerHeight + window.innerHeight, 
    
    0 讨论(0)
  • 2020-12-13 04:27
      window.scrollTo(0,0);  
    

    Add this works for me.

    0 讨论(0)
  • 2020-12-13 04:31

    If you have a height set to the div you want to turn to a canvas - you need to remove that before actually taking the snapshot. Otherwise it will just cut it off because of that height.

     $(".yourElemThatHasSomeHeightSet").css("height", "");
    

    Then you will notice that scrolling down - will still cut your document. Simply do a:

    $("html, body").scrollTop(0);
    

    before taking the snapshot.

    0 讨论(0)
提交回复
热议问题