Drawing DOM objects into a canvas

Although it's not trivial (for security reasons), it's possible to draw DOM content -- such as HTML -- into a canvas. This article, derived from this blog post by Robert O'Callahan, covers how you can do it securely, safely, and in accordance with the specification.

An overview

You can't just draw HTML into a canvas. Instead, you need to use an SVG image containing the content you want to render. To draw HTML content, you'd use a <foreignObject> element containing the HTML, then draw that SVG image into your canvas.

Step-by-step

The only really tricky thing here -- and that's probably an overstatement -- is creating the SVG for your image. All you need to do is create a string containing the XML for the SVG and append to a BlobBuilder with the following parts.

  1. The MIME media type of the blob should be "image/svg+xml".
  2. The <svg> element.
  3. Inside that, the <foreignObject> element.
  4. The (well-formed) HTML itself, nested inside the <foreignObject> .

By using a object URL as described above, we can inline our HTML instead of having to load it from an external source. You can, of course, use an external source if you prefer, as long as the origin is the same as the originating document.

Example

<!DOCTYPE html>
<html>
<body>
<p><canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
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' style='font-size:40px'>" +
                 "<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" +
               "</div>" +
             "</foreignObject>" +
           "</svg>";
var svg = new (self.BlobBuilder || self.MozBlobBuilder || self.WebKitBlobBuilder);
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
svg.append(data);
var url = DOMURL.createObjectURL(svg.getBlob("image/svg+xml;charset=utf-8"));
img.onload = function() {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
};
img.src = url;
</script>
</body>
</html>

The example above will produce the following

example.png

The data variable is set up with the content of the SVG image (which in turn includes the HTML) we want to draw into our canvas.

Then we create a new HTML <img> element by calling new Image(), append data, allocate an object URL, and draw the image into the context by calling drawImage() on load.

Security

You might wonder how this can be secure, in light of concerns about the possibility of reading sensitive data out of the canvas. The answer is this: this solution relies on the fact that the implementation of SVG images is very restrictive. SVG images aren't allowed to load any external resources, for example, even ones that appear to be from the same domain. Resources such as raster images (such as JPEG images) or <iframe> s have to be inlined as data: URIs.

In addition, you can't include script in an SVG image, so there's no risk of access to the DOM from other scripts, and DOM elements in SVG images can't receive input events, so there's no way to load privileged information into a form control (such as a full path into a file <input> element) and render it, then pull that information out by reading the pixels.

Visited-link styles aren't applied to links rendered in SVG images, so history information can't be retrieved, and native themes aren't rendered in SVG images, which makes it harder to determine the user's platform.

The resulting canvas should be origin clean, meaning you can call toBlob(function(blob){…}) to return a blob for the canvas, or toDataURL() to return a Base64-encoded data: URI.

Warning: The canvas is not in fact origin clean at this time in Chrome; this is due to a general WebKit bug that causes documents loaded from object URLs and data: URIs incorrectly having a different origin from their containing documents.

Drawing HTML

Since SVG must be valid XML, you need to parse HTML to get the well-formed output of the HTML parser. The following code is the easiest way to parse HTML.

var doc = document.implementation.createHTMLDocument("");
doc.write(html);

// You must manually set the xmlns if you intend to immediately serialize the HTML
// document to a string as opposed to appending it to a <foreignObject> in the DOM
doc.documentElement.setAttribute("xmlns", doc.documentElement.namespaceURI);

// Get well-formed markup
html = (new XMLSerializer).serializeToString(doc);

Tags (5)

Edit tags

Attachments (1)

FileSizeDateAttached by 
 example.png
No description
6.99 kB01:22, 12 Feb 2012syssgxActions

Attach file