Time for action – exporting an image

We can draw pictures with our Canvas Pad application, but what's the point if we can't save them? HTML5 doesn't have the capability to save files directly to the user's file system because of the security risks. So our options on the client side are pretty limited. We can save the data to localStorage or we can open the image in a new browser window, where the user can save the image using the browser's Save option. We will do the latter because it allows the user to get a real image file they can use.

You can get the image data as a URL from a canvas by calling the toDataURL() method on the canvas element itself (not the context). Then you can open the image URL in another window using window.open(). Let's add a Save button to our toolbar and set the data-action attribute to "save":

<button data-action="save">Save</button>

Next let's add a check for the action in the switch statement of the toolbarButtonClicked() method. When the Save button is clicked, it will get the data URL and then open it:

switch (action.tool)
{
    // code not shown...
    case "save":
        var url = $("#main>canvas")[0].toDataURL();
        window.open(url, "CanvasPadImage");
        break;
}

What just happened?

Now we can export images from the canvas using the context's toDataUrl() method and open them in another browser window so they can be saved by the user.

What just happened?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.245.196