最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML String in Html2Canvas - Stack Overflow

programmeradmin4浏览0评论

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 .html

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

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.

Share Improve this question asked Apr 20, 2013 at 4:32 Manak KapoorManak Kapoor 9823 gold badges12 silver badges21 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

Usually html2canvas renders DOM elements and not html code. But you can create a temporary iFrame, let your html render in that iFrame, and then give the generated DOM to html2canvas.

You find an example in this jsfiddle to play around, or here for your convenience:

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

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

发布评论

评论列表(0)

  1. 暂无评论