html2canvas creates a canvas with a width and heig

2019-07-18 20:23发布

问题:

I'm trying to use html2canvas do what it says on the tin, but it keeps creating a canvas with a width and height of zero. I'm doing this:

var HTMLString = '<p>hello world</p>';
var HTMLStringContainer = document.createElement('div');
HTMLStringContainer.innerHTML = HTMLString;
console.log(HTMLStringContainer);
html2canvas(HTMLStringContainer,{
    onrendered:function(newCanvas){
        document.getElementById("image").appendChild(newCanvas);
    }
});

And when I print HTMLStringContainer it shows <div><p>hello world</p></div>, which looks correct.

Snippet

var HTMLString = '<p>hello world</p>';
var HTMLStringContainer = document.createElement('div');
HTMLStringContainer.innerHTML = HTMLString;
console.log(HTMLStringContainer);
html2canvas(HTMLStringContainer, {
  onrendered: function(newCanvas) {
    document.getElementById("image").appendChild(newCanvas);
  }
});
<script src="https://github.com/niklasvh/html2canvas/releases/download/0.4.1/html2canvas.js"></script>
<div id="image"></div>

Also, jsfiddle: http://jsfiddle.net/4077wxLj/

回答1:

The element to render as a canvas needs to be in the DOM, such as a child of document.body, before it can be rendered.