HTML and CSS Reference
In-Depth Information
their own independent states. Many of the same applications that could make full use
of the canvas (games, activities, animations) are often easier to code with a retained
mode drawing surface, especially for beginners.
Our challenge is to take advantage of the immediate mode drawing surface, while add-
ing functionality to our code to help it act more like it works in retained mode.
Throughout this topic we will discuss strategies that will help take this immediate mode
operation and make it easier to manipulate through code.
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 JavaScript: width and height . These tell you the current width and height of
the canvas rendered on the HTML page. It is important to note that they are not read-
only; i.e., they can be updated in code and changed on an HTML page. What does this
mean? It means you can dynamically resize the canvas on the HTML page without
You can also use CSS styles to change the scale of the canvas. Unlike
resizing, scaling takes the current 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 CSS style:
style="width: 400px; height:400px"
We include an example of scaling the Canvas with a transformation
matrix in Chapter 3 .
There are also 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
retrieve a reference to the Canvas 2D context so we can draw onto the canvas. The
second property 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() in the next application to export
an image of the canvas into another browser window.
Search WWH ::

Custom Search