Five Cool Things About The HTML5 Canvas
- You can easily clear a Canvas by changing the size. Or even resetting the size to itself. However, if you'd like clear only a portion of the canvas, you can use context . clearRect(x, y, w, h) or context . fillRect(x, y, w, h). The difference between the two is that clearRect clears to black and fillRect paints over the rectangle with whatever fillStyle you have set.
- You can save a image from a canvas. toDataURL returns an encoded Base64 string representing the image. You can then use that image data in other canvases or image tags. Please note that toDataURL is on the Canvas object NOT the context. There isn't a standard lib to convert directly to a file in the HTML5 spec but generally you would either use a backing server or decode the data from Base64 and write to a file using the FileWriter API. FileWriter isn't well supported atm.
- You can do pixel manipulation on canvases. To retrieve the ImageData from a canvas, you would call getImageData(0,0, imageWidth, imageHeight) on a CanvasContext. What you get back is an object with properties for the width, height of the the image data and RGBA values for every pixel in the ImageData object. After doing the manipulation, you would call putImageData to push the results into a canvas. Here's an example that converts an image to grayscale.
- You can create multiple canvases on a page. One reason to use multiple canvases is if you want to do alot of manipulation to a particular canvas and don't want to worry about having to save and restore the context. You might want to cache the orientation of an object as Seth Ladd did in his this code for his Google IO talk.
- You can texture a canvas with video. As far as the canvas is concerned, a video is just a series of images that are compatible with the canvas. You can display them on canvases as is or do pixel manipulation. Tab Atkins Jr. has a couple of examples on his site here and here.
Note*: Tab's demos pre-date the advent of requestAnimationFrame by about a year or so.*