Search code examples
javascripthtmlcanvashtml2canvas

HTML String in Html2Canvas


How do we pass a valid HTML String into html2canvas?

e.g

var html = "<html><head></head><body><p>HI</p></body></html>

The way it is done on http://html2canvas.hertzen.com/screenshots.html

Html2canvas is really great and all but it's very poorly documented.


Solution

  • You can do as following

    var iframe=document.createElement('iframe');
    $('body').append($(iframe));
    setTimeout(function(){
        var iframedoc=iframe.contentDocument||iframe.contentWindow.document;
        $('body',$(iframedoc)).html('<html><head></head><body><p>HI</p></body></html>');
        html2canvas(iframedoc.body, {
            onrendered: function(canvas) {
                $('body',$(document)).append(canvas);
                $('body',$(document)).remove(iframe);
            }
        });
    }, 10);
    

    See the whole code here :

    DEMO