HTML and CSS Reference
The HTML5 Canvas Object
Recall that the Canvas object is created by placing the <canvas> tag in the <body> portion of
an HTML page. You can also create an instance of a canvas in code like this:
var theCanvas = document . createElement ( "canvas" );
The Canvas object has two associated properties and methods that can be accessed through
rendered on the HTML page. It is important to note that they are not read-only; that is, they
can be updated in code and changed on an HTML page. What does this mean? It means that
you can dynamically resize the canvas on the HTML page without reloading.
You can also use CSS styles to change the scale of the canvas. Unlike resizing, scaling takes the cur-
rent canvas bitmapped area and resamples it to fit into the size specified by the width and height
attributes of the CSS style. For example, to scale the canvas to a 400×400 area, you might use this
style = "width: 400px; height:400px"
We include an example of scaling the Canvas with a transformation matrix in Chapter 3 .
There are currently two public methods for the Canvas object. The first is getContext() ,
which we used earlier in this chapter. We will continue to use it throughout this topic to re-
trieve a reference to the Canvas 2D context so we can draw onto the canvas.
The second method is toDataURL() . This method will return a string of data that represents
the bitmapped image of the Canvas object as it is currently rendered. It's like a snapshot of
the screen. By supplying different MIME types as a parameter, you can retrieve the data in
different formats. The basic format is an image/png , but image/jpeg and other formats can be
retrieved. We will use the toDataURL() method in the next application to export an image of
the canvas into another browser window.
A third public method, toBlob() , has been defined and is being implemented across browsers.
toBlob([callback]) will return a file reference to an image instead of a base64 encoded string. It
is currently not implemented in any browsers.