HTML5 Canvas to Image using canvas.toDataURL Method
This HTML5 Canvas tutorial shows how to save drawing in canvas to image using HTML5 Canvas toDataURL method. HTML5 introduces web programmers with Canvas drawing space using scripting in Javascript. HTML5 Canvas enables HTML developers to draw image in a HTML embedded space using Javascript canvas objects and methods.
Canvas object has toDataURL method which returns canvas image data and enables developers to save canvas image or set as source of an image element in HTML page.
Using Canvas.toDataURL method, it is also possible to set image data of a canvas element in HTML5 page to an other canvas element too.
Let's start this HTML5 canvas tutorial first with looking at canvas.toDataURL syntax and learning toDataURL method arguments. After web developers get the target canvas element using getElementById() method into a canvas object in Javascript codes, canvas.toDataURL() method can be executed to get binary data from canvas to image.
Canvas object toDataURL() method has two arguments: MIME type for the return image data as string, and the quality level of the return image within in range from "0.0" to "1.0"
As an example to MIME types, HTML developers can use "image/png" or "image/jpg" where "image/png" is the default value. So if you want to return canvas data as an image in .jpg format, you can call toDataURL() method as follows:
Furthermore within the same Javascript block, developers can get an image element in the same HTML page. Then it is possible to set canvas image data as source of HTML image element as follows.
Let's now make an HTML5 canvas web page where we'll code in Javascript to save canvas to image element source. Please copy and paste the following code block in an empty HTML5 page. Or you can visit return canvas image using toDataURL() method for a demonstrating HTML5 page.
The HTML5 page will be similar to as seen in below screenshot
If you save the image file, you can realize that the canvas area except the black rectangle where nothing is drawn is transparent.
I hope web programmers will find this HTML5 Canvas tutorial interesting and useful.