Web developers have long wanted a way to draw arbitrary HTML content into a canvas element for manipulation. It would be nice to be able to draw web content into 3d environments in WebGL, it would be fun to make custom animations and particle effects with web pages, and many more uses you can dream up. Back in 2005, Mozilla landed a drawWindow() API in Firefox which did just that, but because of security concerns it was later pulled and is now only available to chrome content.

But this doesn’t change that web developers want this feature. We’ve seen entire HTML renderers written in JavaScript, but today Mozilla’s Robert O'Callahan has written about an interesting workaround involving SVG. Because you can now draw SVG content to canvas elements through drawImage in all major browsers, you can technically draw HTML content as well by embedding it in the SVG file as a <foreignObject>. Then you turn the SVG into a data URL and render that to the canvas element. Pretty cool!

There are a few caveats, being that in most browsers you cannot get a dataURL out of the canvas without triggering a security warning, however this seems to be changing in at least Firefox very soon. The other issue is that any images in the web content need to be data URLs as well otherwise security errors will be thrown. So there are some issues, but nothing that can’t be worked around with a little JS magic!

Cool stuff! You can read the article yourself here, and check out a demo here. Have fun!