11

I am using the html2canvas library, using the following code:

html2canvas(document.body, {
   onrendered: function(canvas) {
      document.body.appendChild(canvas);
   }
});

When onrendered is fired, the page is automatically scrolled to the top. Is there anyway we can maintain our scroll position and not be automatically taken to the top of the page?

1

2 Answers 2

23
+200

I took a look into the html2canvas.js and saw the following line:

_html2canvas.Parse = function (images, options) {
    window.scroll(0,0);

After commenting window.scroll(0,0) out, it worked fine for me on my local testing. Seems like that behaviour was intended by the author.

Of course you could also save your current scroll position into a variable when firing the code. The way you may do it depends on how you execute html2canvas. If it's a button like on the demo page, you would add an event listener to that button:

var scrollPos;
document.querySelector("screenshotButton").addEventListener("click",function() {
    scrollPos = document.body.scrollTop;
    html2canvas(document.body, {
       onrendered: function(canvas) {
          document.body.appendChild(canvas);
          window.scrollTo(0,scrollPos);
       }
    });
 });
3
  • That's fantastic, I spotted that line also just after I posted my bounty. It's all yours as soon as I can reward it :). Thanks for your help. Jul 29, 2014 at 22:03
  • Perfect! Thank you.
    – lwdthe1
    Jul 22, 2017 at 2:56
  • onrendered no longer exists. Use onclone instead, as shown at html2canvas.hertzen.com/configuration
    – matharden
    Nov 22 at 12:28
1

You should be able to adjust the scrollY position, relative to the current pageYOffset, try this

html2canvas(document.body, { scrollY: (window.pageYOffset * -1) })

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.