Images on a Canvas
Working with images is just as easy. The canvas API drawImage method places an image at a specific location on a canvas with optional scaling factors. The following code example places a United States flag on a world map wherever you click the mouse. Both the map and the flag are from the CIA's World Fact Book. Feel free to choose your own flag or icon to conquer the world. (Note: The image URLs do not contain any blanks.)
Second, an initCanvas function is defined that will establish the canvas 2D drawing context and draw the map at location (0,0) the top-left corner of the canvas (x and y values increase to the right and down, respectively.)
The initCanvas function also defines a event handler that will be called whenever the user clicks on the canvas. The handler function is passed an event object from which it gets the x and y window coordinates of the click. It draws the flag scaled to 48x25 pixels, offset to place the flag's center at the click point.
Figure 2 Map and flagsworking with images on the HTML5 canvas.
These examples demonstrate how easy it is to build useful web applications on the canvas. In the map and flag example, only a few more lines of code would allow the user to pick her own flag or pop up information related to the clicked location. A few other points are worth noting about this example:
- Anything drawn on the canvas becomes part of the canvas's bitmap. A flag, once it is drawn, ceases to exist as a separate image object. It can't be moved around or erased without redrawing the entire map each time before drawing the flag somewhere else, or not at all. Separate graphical objects that can be moved, scaled, erased, and otherwise manipulated, are in the realm of Scalable Vector Graphics (SVG), another part of the HTML5 package that's not as well supported as the canvas element is now.
- The canvas accommodates videos as easily as images. The drawImage method used in the example can be called with either an image or a video object. Both the map and the flag images can be replaced with running videos. Loading a video into a canvas element provides the ability to manipulate video frames at runtime. This is explored in a great blog post, “Blowing Up HTML5 Video and Mapping It into 3D Space,” by Sean Christmann.
- Everything is out in the open! This is bad news for producers. It is difficult to protect the intellectual property value of a canvas application's code. Anyone can take a copy, rebuild, and deploy it for their own profit, leaving no recourse other than to sue after the fact. There are also source origin problems with the canvas where the bits and pieces of the content and code can reside on different servers in multiple Internet domains, providing opportunities for confusion and abuse.