To display HTML within a canvas, you can utilize SVG along with its foreignObject
element. However, this method has limitations as it does not support rendering images or external sources directly (they must be extracted and rendered separately).
CHECK OUT THE LIVE DEMO HERE
Outcome:
Let's define the HTML content that we intend 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>
We can then construct an inline SVG and insert the HTML content using the html
id of the initial 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>";
The next step involves creating a Blob
object to reference the SVG as a URL that can be used with the canvas for image rendering:
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"} );
// create a URL that can be used for the image tag
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
// now we can draw the "html" content onto the canvas
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
This process can be wrapped into a function that accepts an id and canvas as parameters, handling external content and images accordingly.