CSS Canvas Drawing

Currently the set of images you can use from CSS consists of the following:

Bitmap Images (PNG, GIF, JPG)
SVG Images
Gradients

A notable missing ability when compared with explicit DOM content is programmatic drawing into CSS images. The <canvas> element represents a foreground bitmap image that can be drawn into programmatically, but – aside from inefficient hacks involving toDataURL – there hasn’t been any way to draw into the image buffers used by CSS images.

Until now!

In the latest nightlies, you can try out a new feature: the ability to specify named image buffers in CSS and then to draw into them programmatically from JavaScript. Here’s how it works.

background: -webkit-canvas(mycanvas);

Instead of specifying an image URL, you specify a canvas and an identifier to use for that canvas. The following new API on documents can then be used to obtain a drawing context for that canvas.

CanvasRenderingContext getCSSCanvasContext(in DOMString contextType, in DOMString identifier, in long width, in long height);

There is only one CSS canvas for a given global identifier per document. When you obtain the drawing context you also specify the size. The canvas will not be cleared as long as you repeatedly request the same size. Specifying a new size is equivalent to the kind of behavior you’d expect if you resized a <canvas> element, and so the canvas buffer will be cleared.

All objects that observe a CSS canvas of the same name are sharing that canvas. This means that (similar to how animated GIFs work), you can do animations and have them happen in lockstep on all the clients of the canvas. Drawing changes will be propagated to all clients automatically.

Here is an example:

Canvas as Background Image