Search code examples
javascriptjqueryhtmlhtml2canvas

How do I take a screenshot using HTML2Canvas for a jQuery element?


I'd like to use HTML2Canvas to take a screenshot (base64 representation) of a jQuery selectable list. However, it seems to be unable to interpret the jQuery element.

This is how I'm taking the screenshot.

    html2canvas(document.getElementById("target"), {
        onrendered: function (canvas) {
            var dataURL = canvas.toDataURL();
            console.log(dataURL);
        }
    });

It works for taking a screenshot of a regular HTML element so I'm not sure what to do now.

Here is the JSFiddle, make sure to open your console.


Solution

  • html2canvas works by computing the style of the element using, element.getComputedStyle().

    The #target element that you are using doesn't have any height to it. So during the canvas rendering it computes the height to 0. So you won't be able to see any data.

    Try setting a min-height to it. That should solve the issue. You should also specify proper width otherwise the data wont be captured completely.

    #target {
          min-height:300px;
    }
    

    Or

    Update much cleaner way, clear the float that you are using in #selectable.

       #selectable:after{
         content: "";
          display: block; 
          clear: both;
       }