HTML and CSS Reference
In-Depth Information
What's a data URL?
Most browsers support being able to read base64 encoded assets, such as an image. The URL scheme
looks like this:
It starts with data, then the mime type, then the encoding, base64, and then the raw data. This raw data is
what's exported by the canvas element, and browsers are able to decode the data in to real assets (sadly,
this doesn't include IE7 or previous incarnations of IE). In addition, IE8 only supports data URLs up to a
length of 32Kb—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 specifi ca-
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 fi le format). Firefox (on a Mac) supports only
PNG, throwing an error on all other types (which is 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 the return format is what you
asked for.
The following example generates a similar drawing from the
hello world drawing and immediately saves it to a PNG by redi-
recting the browser to the rendered image:
var ctx = document.querySelector('canvas').
¬ getContext('2d');
ctx.fillStyle = 'rgb(0, 0, 255)';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillStyle = 'rgb(0, 255, 0)';
ctx.fillRect(10, 20, 50, 50); // little square
window.location = ctx.canvas.toDataURL('image/png');
Finally, the toDataURL also takes an optional second argument
that is available only if image/jpg has been implemented to allow
you to specify quality level of the image generated. This value
would be between 0.0 and 1, with 1 being the highest quality
available, and it affects the size of the base64 data generated
from toDataURL .
Search WWH ::

Custom Search