HTML and CSS Reference
In-Depth Information
Saving the Canvas Drawing in an <img> Object
At times you may want to allow users to save the canvas drawing as a physical image file. In such cases,
saving a canvas drawing as an image can be useful. Once the image has been saved, users can right-click it
and save the drawing in their local file system just like any other image loaded in the browser.
Saving a canvas as an image can also be used in situations where you wish to allow users to create
multiple drawings without saving them explicitly and then load the previously created drawings again on
the canvas. In such cases, you can save different drawings as images and then reload the drawings using
the drawImage() method discussed earlier.
Saving a canvas drawing in an <img> object is straightforward. All you need to do is assign the src
property of the DOM <img> element to the Base64-encoded data returned by the toDataURL() method.
Listing 4-20 shows how this can be done.
Listing 4-20. Saving a Canvas Drawing as an <img> Object
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
context.fillRect(20, 20, 160, 160);
var data = canvas.toDataURL();
$("#imgCanvas").attr("src", data);
As shown in this listing, a rectangle is drawn on the canvas, and then toDataURL() is called to retrieve
the Base64-encoded representation of the canvas drawing. You load this Base64 data into an <img> element
by setting its src attribute. A part of a sample Base64-encoded string is shown here:
As you can see, the string begins with a MIME type for the image. You can also specify the image type
yourself using a variation of toDataURL() :
var data = canvas.toDataURL("mage/png");
toDataURL() now takes the MIME type for the image. Typical values include image/png and image/jpg .
The default image MIME type is image/png .
Saving the Canvas Drawing in SQL Server
Saving the canvas drawing in a SQL Server database calls for sending to the server the Base64-encoded
data obtained as a result of calling toDataURL() . You can either use a hidden form field to accomplish this
data transfer or, better yet, use the jQuery $.ajax() method. Listing 4-21 uses $.ajax() to send the Base64-
encoded data to the server.
Listing 4-21. Sending Base64 Canvas Data to the Server Using $.ajax()
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
context.fillRect(20, 20, 160, 160);
$('#btnSave').click(function () {
var data = canvas.toDataURL();
data = data.replace('data:image/png;base64,', '');
type: 'POST',
Search WWH ::

Custom Search