Search code examples
javascriptcsshtml2canvas

html2canvas render only the visible part of div element


I'm using html2canvas to screenshot a scrollable div element in the page. However, it only renders the what is visible instead of whole div.

Here is a small example: https://codepen.io/johnhckuo/pen/abpGrmr

I've done some searching and see others recommend setting scrollY: -window.scrollY in the html2canvas parameter. But it doesn't work for me.

Does anyone have experience on this issue? Thank you!


Solution

  • Try adding a child element to #photo, which is not constrained by CSS - like this:

    <div id="photo">
    <div id = "photo-inner">
            <button onclick="takeshot()">
            Take Screenshot
        </button>
        <h1>Test</h1>
        Hello everyone! This is a
        trial page for taking a
        screenshot.
        <br><br>
        This is a dummy button!
        <button> Dummy</button>
        <br><br>
        Click the button below to
        take a screenshot of the div.
        <br><br>
        <button onclick="takeshot()">
            Take Screenshot
        </button>
    </div>
    </div>
    

    Then, make the child element the target of html2canvas:

    let div = document.getElementById('photo-inner');
    

    (This works in your Codepen, which I can't fork, as I'm not signed up.)