Home > Articles > Web Development > HTML/CSS

  • Print
  • + Share This
From the author of Feature #4: Image Manipulation

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.

  • + Share This
  • 🔖 Save To Your Account