Search code examples
javascriptjqueryhtmlcsshtml2canvas

Targeting a specific div with html2canvas


I'm using Hertzen's html2canvas.js, and tried to adjust the example code so that it targets a specific div instead of the entire body of a document:

html2canvas(document.body, {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  }
});

A sample of what I'm trying to accomplish is here: https://jsfiddle.net/ununkg3a/

On clicking the "Save PNG" button, I want to append an image of the jQuery generated squares that I'm targeting in a specific div. In the code, it appears that it's appending something, but it doesn't have a height. When I try to set a height with the output, it still doesn't work as expected.

Is it not possible to accomplish something like this? Whenever I change document.body to another element, the screenshot doesn't render anymore, although it does render when I change it back to document.body. Someone told me that I'd have to crop the image with js, but that seems a little hacky.


Solution

  • It can: it's the first attribute. (fiddle)

    Example:

    html2canvas(document.getElementById('test')).then(function(canvas) {
        document.body.appendChild(canvas);
    });
    

    In your example, canvas2html can't find out the height of your div. Because of that it falls back to 0px height, so you won't see anything.

    Give width to the #art then you can count the height manually and use that.

    Mathematic example:
    art_square_width = 10px
    art_square_height = 10px
    art_square_amount = 500
    art_width = 250px
    art_height = art_width / (art_width / art_square_width) * art_square_height = 200px

    (fiddle)