HTML and CSS Reference
In-Depth Information
Exporting Canvas to an Image
Earlier, we briefly discussed the toDataUrL() property of the Canvas object. We are going
to use that property to let the user create an image of the game screen at any time. This acts
almost like a screen-capture utility for games made on Canvas.
Weneedtocreate abuttonintheHTMLpagethat theusercanpresstogetthescreen capture.
We will add this button to <form> and give it the id createImageData :
<form>
<form>
<input
<input type= "button" id= "createImageData" value= "Export Canvas Image" >
</form>
</form>
In the init() function, we retrieve a reference to that form element by using the getEle-
mentById() method of the document object. We then set an event handler for the button
“click” event as the function createImageDataPressed() :
var
var formElement = document . getElementById ( "createImageData" );
formElement . addEventListener ( 'click' , createImageDataPressed , false
false );
In canvasApp() , we define the createImageDataPressed() function as an event handler.
This function calls window.open() , passing the return value of the Canvas.toDataURl()
methodasthesourceforthewindow.Sincethisdataformsavalid .png ,theimageisdisplayed
in the new window:
function
function createImageDataPressed ( e ) {
window . open ( theCanvas . toDataURL (), "canvasImage" , "left=0,top=0,width=" +
theCanvas . width + ",height=" + theCanvas . height + ",toolbar=0,resizable=0" );
}
NOTE
We will discuss this process in depth in Chapter 3 .
Search WWH ::




Custom Search