3

I am trying to capture the screenshot of a portion of the web-page in my web app using the following code.

function getScreenshot(){
  var content = document.querySelectorAll("div.class")[0];
  setTimeout(function(){captureScreenshot()},10);
  function captureScreenshot() {
    html2canvas(content, {
        onrendered: function(canvas) {
            var newImg = document.createElement("img");
            newImg.src = canvas.toDataURL();
            var newAnchor = document.createElement("a");
            newAnchor.href = newImg.src;
            newAnchor.download = "screenshot.png";
            newAnchor.id="screenshot";
            document.body.appendChild(newAnchor);
            newAnchor.click();
        }
    });
  }
}

The above code works just fine across all the browsers and I can get the png just fine. However if i call captureScreenshot method without the setTimeout it does not quite work? i.e. nothing gets drawn on the canvas.

function getScreenshot(){
  var content = document.querySelectorAll("div.class")[0];
  captureScreenshot();
  function captureScreenshot() {
    html2canvas(content, {
        onrendered: function(canvas) {
            var newImg = document.createElement("img");
            newImg.src = canvas.toDataURL();
            var newAnchor = document.createElement("a");
            newAnchor.href = newImg.src;
            newAnchor.download = "screenshot.png";
            newAnchor.id="screenshot";
            document.body.appendChild(newAnchor);
            newAnchor.click();
        }
    });
  }
}

I have tried stepping through the source of html2Canvas but I still cant seem to work out why I need a timeout? My solution works, but I just need to know exactly what is causing the timeout to be necessary?

Ok so just some additional info, on Chrome and IE it works most of the time without the timeout, but on Firefox, it never works without the timeout.

cptdanko
  • 812
  • 2
  • 13
  • 22
  • I think what might happen is that the browser needs a couple of milliseconds to actually draw stuff, so if you take the screenshot too soon nothing will be there to be screenshotted (is that even a word?). Just guessing.. – Jonas Grumann Oct 28 '14 at 09:42
  • yes but if i log out the "content" variable, I can see the html content in the console. – cptdanko Oct 28 '14 at 10:06
  • maybe because you are calling the function before it is defined? The ten milliseconds is long enough for the function to be defined... – lukeocom Oct 29 '14 at 04:36
  • Cheers for the suggestion, but that does not solve the problem either. – cptdanko Oct 30 '14 at 03:12

0 Answers0