A few months ago, I had to add a feature to this web app at work that would enable the users to get a screenshot of the page they are on. When I was given this problem to solve, I thought surely someone must have solved this problem? so I started looking for a library that would help me achieve this. After a bit of searching I came across the html2canvas library which is awesome and it really does get the job done. I am not going to get into details about how the html2canvas library works, I think it’s documentation does a good job of it. Anyway my javascript code to capture the screenshot was something like this.

function getScreenshot(callbackFunc){
var content = document.querySelectorAll("divToCapture")[0];
setTimeout(function(){screenCap();},0);

function screenCap(){
html2canvas(content, {
onrendered: function(canvas) {
callbackFunc(canvas.toDataURL());
}
});
}
}

So the above function is pretty self-explanatory, however I must provide a bit of context to make things more clear. Ok so the web app that I had to add this feature to was a GWT based, so I am passing a callback function that would take the contents of the canvas once html2canvas finishes drawing them.

Now this line of the code

setTimeout(function(){screenCap();},0);

might seem a little bit strange, why not just call the screenCap method would a timeout. Well so at least for the web app that I was working with, the above code without the timeout was working just fine on Chrome and IE but not on Firefox. What was happening on Firefox was that the downloaded image would be blank without the timeout. I tried to find an explanation for this, but I was not very successful. I posted a question on Stackoverflow as well, but could not quite find an answer.

So my conclusion was, since Javascript is single-threaded, and one of the things setTimeout does is push the execution of the function down the execution chain.




Leave a Reply

Your email address will not be published. Required fields are marked *