- Feature #10: Path-Based Graphics and the Nonzero Winding Rule
- Feature #9: Hit Detection
- Feature #8: canvas Is an HTML Element
- Feature #7: Temporary Drawing
- Feature #6: Offscreen Canvases
- Feature #5: Transforming the Coordinate System
- Feature #4: Image Manipulation
- Feature #3: Drawing Images and More with drawImage()
- Feature #2: The Clipping Region
- Feature #1: New Functionality in the 2D API
- Conclusion
Feature #4: Image Manipulation
As I discussed in the earlier section "Feature #7: Temporary Drawing," the 2D API's getImageData() method lets you capture all or part of the pixels of an image, and the putImageData() method inserts a rectangle of pixels into an image. Between those two calls, you can manipulate the image. For example, the application shown in Figure 7 uses those two methods to implement an embossing image filter.
Figure 7 An embossing filter that uses HTML5 Canvas image manipulation.
Here's how the filter works:
function emboss() { var imagedata, data, length, width, index=3; imagedata = context.getImageData(0, 0, canvas.width, canvas.height); data = imagedata.data; length = data.length; for (i=0; i < length; i++) { // loop through every pixel // Modify the pixel data here... } context.putImageData(imagedata, 0, 0); }
The preceding JavaScript uses getImageData() to grab all the image's pixels; then it goes into a loop, where it modifies that pixel data. Finally, the function puts the modified image data back into the canvas.