5.12 Base64 Encoding with “canvas.toDataURL( )” 163
context.setTransform(1,0,0,1,60,160);
context.transform(1,Math.tan(-0.175),0,1,0,0);
context.translate(3200.1,Math.tan(0.175)320);
context.scale(0.9,1);
context.drawImage(icons[0],0,0,320,320);
context.drawImage(effects[0],0,320,320,160);
We have now completed our most difficult Canvas example so far. The result is
quite impressive, so we should probably save it as JPEG or PNG file. Unlike the
other browsers, Firefox makes it easy for you—just right-click on the canvas to
save your creation. If you click on View Image, a bizarre and very, very, very long
URL address appears, starting with data:image/png;base64..., which takes us
straight to the next section—canvas.toDataURL().
5.12 Base64 Encoding with “canvas.toDataURL()”
Base64 describes a method of encoding binary data as ASCII strings. In Canvas it
is used to turn the canvas content, which only really exists as raster in memory,
into a processable data: URL. The method to achieve this is
canvas.toDataURL(type, args)
We pass the MIME type of the desired output format as type using either image/
png or image/jpeg. The former is the default encoding format and is also used if
we omit type or specify a format with which the browser cannot cope. Any ad-
ditional parameters can be accommodated by the optional argument args—for
example, the image quality if selecting image/jpeg with valid numbers between
0.0 and 1.0.
The result of toDataURL() is a base64-encoded string. In the case of the 2 × 2 pixel
canvas in the named colors navy, teal, lime, and yellow of Figure 5.27, it looks
as follows:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUg
AAAAIAAAACCAYAAABytg0kAAAAF0lEQVQImQXBAQEAAA
CCIKb33ADLFql0PuYIemXXHEQAAAAASUVORK5CYII=
These encoded strings can get rather long. The base64 version of our photo col-
lage with the reflection effect, for example, has no less than 1,298,974 characters
and would fill 325 pages of this book (with each page containing 50 lines of 80
characters each)!
So what is toDataURL()used for? Why convert binary image data to charac-
ter strings? The answer is simple: With toDataURL(), we can make the fleeting