问题
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.
来源:https://stackoverflow.com/questions/26604942/cant-draw-the-contents-of-a-div-onto-a-canvas-using-html2canvas-without-a-timeou