HTML and CSS Reference
In-Depth Information
The toDataURL() Method of the Canvas Object
As we briefly explained in Chapter 1 , the Canvas object also contains a method named
toDataURL() , which returns a string representing the canvas's image data. A call with no ar-
guments will return a string of image data of MIME type image/png . If you supply the image/
jpg as an argument, you can also supply a second argument between the numbers 0.0 and 1.0
that represents the quality/compression level of the image.
We are going to use toDataURL() to output the image data of the canvas into a <textarea>
on our form and then open a window to display the actual image. This is just a simple way to
show that the function is working.
by creating a button with the id of createImageData that, when pressed, will create the im-
age data with a call to an event handler named createImageDataPressed() .
We also create a <textarea> named imageDataDisplay that will hold the text data of the
image after the createImageData button is pressed:
<input type= "button" id= "createImageData" value= "Create Image Data" >
<textarea id= "imageDataDisplay" rows= 10 cols= 30 ></textarea>
Next, we set up the event listener for the createImageData button:
formElement = document . getElementById ( "createImageData" );
formElement . addEventListener ( 'click' , createImageDataPressed , false
false );
Then,inthe createImageDataPressed() eventhandler,wecallthe toDataURL() methodof
the Canvas object ( theCanvas ) and set the value of the imageDataDisplay <textarea> to
the data returned from toDataURL() . Finally, using the image data as the URL for the win-
dow,wecall .When wedothis, awindowwill popopen,displaying the actu-
al image created from the canvas. (See Figure 3-11 .) You can right-click and save this image,
just like any other image displayed in an HTML page. Pretty cool, eh?
function createImageDataPressed ( e ) {
var imageDataDisplay = document . getElementById ( 'imageDataDisplay' );
imageDataDisplay . value = theCanvas . toDataURL ();
window . open ( imageDataDisplay . value , "canvasImage" , "left=0,top=0,width=" +
theCanvas . width + ",height=" + theCanvas . height +
Search WWH ::

Custom Search