2

i need to convert my html div to canvas and i am using html2canvas right now but it only captures the visible part of the window. i mean to say it is not capture the whole dive which has horizontal scroll.

So is there any way to capture whole div with horizontal scroll or any suggestion in html2canvas for the same.

here is the code i used

var element = document.getElementsByClassName('ppm_portlet_data');

    html2canvas(element[0], { width: element[0].offsetWidth, height: element[0].offsetHeight }).then(function (canvas) {
            console.log(canvas.toDataURL());
            Canvas2Image.saveAsPNG(canvas);
            console.log(canvas.width, canvas.height);
         });
2
  • Please post the code on which you're working Commented Oct 3, 2018 at 6:30
  • i have added please review it Commented Oct 3, 2018 at 7:58

1 Answer 1

2

You have to use scrollWidth & scrollHeight and set overflow: visible; in order to get content that is not visible.

Working Example

const div = document.querySelector('#content');
div.innerText = div.innerText.split(' ').join(''); // just for overflowing content

div.addEventListener('click', event => {
    html2canvas(div, { width: div.scrollWidth, height: div.scrollHeight }).then(canvas => {
        document.body.appendChild(canvas);
        console.log(canvas.width, canvas.height); // outputs greater width than browser width
    });
});
#content {
    overflow: visible; /* make overflow visible to capture */
    word-wrap: nowrap;
}
<body>
    <div id='content'>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus.
    </div>

  <script type="text/javascript" src='https://html2canvas.hertzen.com/dist/html2canvas.min.js'></script>
</body>
Sign up to request clarification or add additional context in comments.

4 Comments

the canvas height and width are same as the scroll height and width but the image is cutting or captured just shown in the window screen
thanks for the solution, scrollWidth & scrollHeight helped me to solve the issue i was facing.
I just want to use vanilla js, convert HTML to canvas, then canvas to an image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.