HTML and CSS Reference
Saving to file
Yo u ' v e m a d e t h e n e x t b e s t t h i n g s i n c e s l i c e d b r e a d ? W a n t t o
save your beautiful drawing to your desktop? You want to export
it in multiple formats? No problem. Canvas has you covered.
The canvas element (not the 2D context) supports exporting the
current state of the canvas to a data URL.
What's a data URL?
Most browsers support Base64 encoded assets, such as an image. Web applications like Gmail use
Base64 encoded images in their CSS to reduce the number of requests being made over the wire (even
though it actually makes the CSS file larger as all the image data is embedded). The URL scheme looks
It starts with data, then the mime type, then the encoding, Base64, and then the raw data (which roughly
speaking is 30 percent larger than the source image). This raw data is what's exported by the canvas ele-
ment, and browsers are able to decode the data in to real assets (sadly, this doesn't include IE7 or previ-
ous incarnations of IE). In addition, IE8 only supports data URLs up to a length of 32 KB—something to
watch out for!
Exporting is very easy. The canvas has the toDataURL method,
which can be invoked with the format in which you want your
image. Only PNG support is required by the canvas specifica-
tion, but browsers can support other types if they choose. For
example, Safari supports GIF, PNG, and JPG. Trying to get the
data URL for an unsupported TIFF format returns exclusively
the letter A multiple times and no data:<mime-type> . Opera sup-
ports only PNG, but on requesting a JPG or GIF, it still returns
a PNG (ignoring the file format). Old versions of Firefox (on a
Mac) supported only PNG, throwing an error on all other types
(which was a little severe if you ask me). The lesson here is that
once you have your data URL back, ensure that it starts with
data:< your-mime-type > to ensure that they match up and that
you get back the image in the format you asked for.
The following example generates a drawing similar to our hello
world example and immediately saves it to a PNG by redirecting
the browser to the rendered data URL: