Cant draw the contents of a div onto a canvas using Html2Canvas without a timeout

微笑、不失礼 提交于 2021-01-27 15:50:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!