javascript - Html2Canvas 中的 HTML 字符串

标签 javascript html canvas html2canvas

我们如何将有效的 HTML 字符串传递给 html2canvas?

例如

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

http://html2canvas.hertzen.com/screenshots.html 上完成的方式

Html2canvas 确实很棒,但它的文档却很少。

最佳答案

通常 html2canvas 渲染 DOM 元素而不是 html 代码。但是你可以创建一个临时的 iFrame,让你的 html 在那个 iFrame 中呈现,然后将生成的 DOM 交给 html2canvas。

您可以在 jsfiddle 中找到示例玩,或在这里为了您的方便:

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);

关于javascript - Html2Canvas 中的 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16116592/

相关文章:

javascript - 如何让 onmouseover 交换事件保持到 onmouseout 直到下一个 onmouseover 事件?

javascript - 可以在模板中缩进行而不缩进内容吗?

javascript - 如何在特定时间禁用点击事件处理程序?

javascript - 在文本选择之前/之后添加元素

javascript - 如果 HTML 文本太大,请添加省略号

HTML5 Canvas : Why does measuring text with measureText and offsetWidth() give different values?

javascript - 基本动画效果——我应该使用 jQuery 还是 HTML5 Canvas?

javascript - getImageData 为 1 个像素返回 4 个值

Javascript 代码可以在 Safari 中运行,但不能在 Firefox 中运行。为什么?

html - 如何让 SVG 容器拥抱它的内容?