HTML and CSS Reference
Notice that in Figure 4-22, the top three rectangles are drawn without using save() or restore() . The
third rectangle assumes the canvas settings set for the second rectangle.
The rectangles at the bottom, however, use save() and restore() . After the code draws the first
rectangle, the canvas state is saved using save() . Before the third rectangle is drawn, the canvas state is
restored using restore() . That's why the third rectangle assumes the restored settings and not those with
which the second rectangle was drawn.
Saving the Canvas Drawing
In the preceding sections you performed drawing operations during the active browser session. What if
you close the browser window? What if you wish to persist a drawing for later use? That is where you need
to deal with saving the canvas drawing. You may want to save the canvas drawing in a storage medium
such as local storage (discussed in Chapter 7), a physical file system of the server, or a SQL server database
residing on the server, so you can retrieve it later during the same or a different browser session.
To fulfill this requirement, the canvas (not the drawing context!) offers the toDataURL() method.
However, this method alone won't persist data on the server. It returns a Base64 representation of the
canvas drawing. It's your responsibility to send this Base64-encoded data to the server using a client-side
technique such as the jQuery $.ajax() method.
In addition to the built-in techniques of saving the canvas drawing, you can implement custom
techniques that mimic a save operation. For example, you can remember all the drawing steps performed
by a user on the canvas. Instead of saving the canvas drawing, you can save these steps on the server and
later replay the same steps to reproduce the canvas drawing. The saving mechanism you use depends on
the kind of application you're building. The following sections you primarily focus on the built-in
techniques for saving the canvas drawing.
Using the toDataURL() Method
The canvas's toDataURL() method returns a Base64-encoded representation of the drawing. It's up to you
to decide what to do with this Base64 data. Some of the possibilities include the following:
• Display the canvas drawing in an HTML image object.
• Send the Base64-encoded string to the server, and save it in a database.
• Send the Base64-encoded string to the server, and save it as an image ile on the
• Save the Base64-encoded string in web storage, and retrieve it later.
Your selection of a canvas-saving technique depends on the kind of application. In the following
examples, you learn all the techniques except the last one; web storage is the subject of Chapter 7.
n Note Base64 encoding is commonly used in scenarios where there is a need to convert binary data to text
format for the sake of storing and transferring over wire. Base64 is commonly used to encode e-mail attachments
and store binary data in XML documents.