将div及其相关元素转换为canvas jquery?

将div及其相关元素转换为canvas jquery?

问题描述:

有什么方法可以将HTML Div及其相关元素转换为canvas,将canvas转换为image使用Jquery?我已经看了下面的网站,它只会转换整个HTML页面和渲染到body.Can任何人帮助我找到它。

Is there any way to convert HTML Div and its associated elements to canvas and the canvas to image Using Jquery? I already had a look on following website, It would only convert whole HTML page and render to body.Can anyone help me find it out.

您可以通过转到SVG及其 foreignObject 将HTML转换为画布。这是有限的,你无法以任何方式(您需要提取它们,并在以后单独渲染它们)。

You can render HTML into canvas by going by SVG and its foreignObject. This is limited in the way you can't render images or external sources in any way (you would need to extract those and render them separately later).

在线示范

ONLINE DEMO HERE

结果:

让我们定义一些我们要渲染的HTML:

Lets define some HTML we want to render:

<div id="html">
    <div style="border:2px dotted #f73;font:12px sans-serif">
        <em>This</em> is
        <span style="color:#00f;border:1px solid #777;padding:0 4px">HTML</span>
        drawn into <strong>canvas</strong>
    </div>
</div>

现在我们可以构建一个内联的SVG并使用 html 第一个div标记的ID:

Now we can build an inline SVG and add this html using the html id of the first div tag:

var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
           "<foreignObject width='100%' height='100%'>" +
           "<div xmlns='http://www.w3.org/1999/xhtml'>" + 

           /// extract the html content of div
           document.getElementById('html').innerHTML +

           "</div>" +
           "</foreignObject>" +
           "</svg>";

下一步是构建一个 Blob 对象所以我们可以引用SVG作为url,在画布上使用它作为一个图像:

Next step is to build a Blob object so we can reference the SVG as url to use with canvas where we draw it as an image:

var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"} );

/// create an url that we can use for the image tag
var url = DOMURL.createObjectURL(svg);
img.onload = function () {

    /// now we can draw the "html" to canvas.
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
};
img.src = url;

您可以将此包装到一个函数中,该函数将id和canvas用作参数,处理外部内容,图片。

You can wrap this into a function that takes an id and canvas as argument and deals with external content and images.