18

Painting on a Canvas background

Static backgrounds are old news, yet even the newer methods (however cool they might be) are still about static images. Wouldn't it be great if we could create dynamic backgrounds? How about animated backgrounds — we could put Nyancat everywhere! Or even creating content-dependent backgrounds? When we combine the power of Canvas with the ability to use it as a background, we can!

What are we talking about?

This is some text that will be connected with an arrow to the next paragraph!

Another paragraph of sorts

And the last one

Some more connected text from top to top

Live drawing on the canvas. Fun feature: try resizing your browser window!

So how do I cook this up?

There are some discrepancies between WebKit (Chrome/Safari) and Firefox so we'll describe each method separately. No other browsers support this yet, as far as we know.

WebKit

The WebKit implementation is by far the easiest: in your CSS you set background-image: -WebKit-canvas("mycanvas"). In the JS, instead of using an existing canvas context, you get the background canvas context with: var ctx = document.getCSSContext("2d", "mycanvas", width, height). You can now draw on this canvas.

Firefox

Firefox works slightly differently in that it uses background-image: -moz-element(#mycanvas) instead of -webkit-canvas("mycanvas"). The element() function can use any DOM element as a background, but you can also assign a canvas element that's not even in the DOM to it. Assigning a canvas that's not in the DOM is done by calling document.mozSetImageElement("mycanvas", canvas);. Don't forget to set the canvas width and height!

Other than the things described above, it works like pretty much any regular canvas and regular canvas context.

What's this for?

It's definitely useful, as it allows us to create flexible backgrounds. We could draw video on a background, improve background-images with layering a canvas image on top of it, or just do the entire background in canvas. The example above is just one of many applications.

But is it ready to be served?

The WebKit variant is non-standard, and even though the element() function is defined in the CSS Image Values and Replaced Content Module Level 4, the only current implementation is Firefox. Some use cases can be hacked around in newer IE's by using the toDataURL() function of the canvas. This creates a data-URL and sets that as a background image.

Show me the source!

Feel free to look around the differente source files we used for this example.