Canvas Cheat Sheet

HTML5 has brought some exciting new advantages to the HTML coding world. Canvas allows you to render graphics powered by Javascript. So throw away that flash code and dive into Canvas. Here you will find the best tutorials and resources to learn Canvas and other HTML5 aspects.

To get the image data URL of the canvas, we can use the toDataURL() method of the canvas object which converts the canvas drawing into a 64 bit encoded PNG URL. If you'd like for the image data URL to be in the jpeg format, you can pass image/jpeg as the first argument in the toDataURL() method. If you'd like to control the image quality for a jpeg image, you can pass in a number from 0 to 1 as the second argument to the toDataURL() method.

Note: The toDataURL() method requires that any images drawn onto the canvas are hosted on a web server with the same domain as the code executing it. If this condition is not met, a SECURITY_ERR exception is thrown.

When HTML5 Canvas applications require multiple images, it's usually a good idea to load all of the images before drawing on the canvas. To simplify the loading process, it's convenient to use an image loader function that takes in a hash of image sources, creates an hash of images, and then calls a user defined function whenever all of the images have loaded.

To get the image data for each pixel of a rectangular area on the canvas, we can get the image data object with the getImageData() method of the canvas context and then access the pixel data from the data property. Each pixel in the image data contains four components, a red, green, blue, and alpha component. There are three common techniques for accessing pixel data with the image data object.

iterating over all of the pixels starting from the top left corner to the bottom right corner of the region

picking out pixel data based on x, y coordinates

iterating over all of the pixels while keeping track of the x, y coordinates for each pixel

Note: The getImageData() method requires that the image is hosted on a web server with the same domain as the code executing it. If this condition is not met, a SECURITY_ERR exception will be thrown.

To grayscale the colors of an image with HTML5 Canvas, we can iterate over all of the pixels in the image, calculate the brightness of each, and then set the red, green, and blue components equal to the brightness.

Note: The getImageData() method requires that the image is hosted on a web server with the same domain as the code executing it. If this condition is not met, a SECURITY_ERR exception will be thrown.

To vertically align text with HTML5 Canvas, we can use the textBaseline property of the canvas context. textBaseline can be set with one of the following values: top, hanging, middle, alphabetic, ideographic, and bottom. Unless otherwise specified, the textBaseline property is defaulted to alphabetic.