164 Chapter 5—Canvas
in-memory canvas permanently available in HTML, enabling the user or an ap-
plication to save it.
The first use of toDataURL() is copying a Canvas graphic into an HTMLImageEle-
ment. This becomes possible because the src attribute can also be a data: URI.
The necessary code is short and requires an empty image in addition to a dy-
namically created canvas:
<!DOCTYPE html>
<title>Copy canvas onto image</title>
<img src="" alt="copied canvas content, 200x200 pixels">
<script>
var canvas = document.createElement("CANVAS");
canvas.width = 200;
canvas.height = 200;
var context = canvas.getContext('2d');
context.fillStyle = 'navy';
context.fillRect(0,0,canvas.width,canvas.height);
document.images[0].src = canvas.toDataURL();
</script>
The crucial line in the listing is printed in bold and shows how easy it is to copy—
define the reference to the first image in the document and specify its src attri-
bute as canvas.toDataURL(). As a result, we get a regular img element, which we
treat just like any other image in the browser and can save as PNG.
With a simple onclick handler on the canvas element, we demonstrate the next
use of toDataURL()—directly assigning the resulting data: URI as URL, but this
time the output is not as PNG, but as JPEG:
document.images[0].onclick = function() {
window.location = canvas.toDataURL('image/jpeg');
};
The disadvantages of this method are that the URL can get painfully long some-
times (remember the 1.3 million characters?), and the fact that images in this
format do not end up in the cache and therefore must be created anew with
every call. Other potential applications of toDataURL() are with localstorage or
XMLHttpRequest, allowing saving and accessing existing Canvas graphics both
on the client side and server side. toDataURL() also serves us well for creating
CSS styles with background-image or list-style-image where we can insert it as
url() value.