Apr
16
2009

 

This example uses Canvas to flip an image.  For introduction to Canvas, please see http://www.permadi.com/tutorial/jsCanvasGrayscale/index.html.

With Canvas, developers gains the access to pixels data of any images loaded.  To flip an image, we can iterate every row of the image and copy the pixels backward. 

[c]
function flipImage(image)
{
  var myCanvas=document.createElement("canvas");
  var myCanvasContext=myCanvas.getContext("2d");

  var imgWidth=image.width;
  var imgHeight=image.height;
  // You'll get some string error if you fail to specify the dimensions
  myCanvas.width= imgWidth;
  myCanvas.height=imgHeight;
 //  alert(imgWidth);
  myCanvasContext.drawImage(image,0,0);
  // this function cannot be called if the image is not rom the same domain.  You'll get security error
  var imageData=myCanvasContext.getImageData(0,0, imgWidth, imgHeight);

  // Traverse every row and flip the pixels
  for (i=0; i<imageData.height; i++)
  {
   // We only need to do half of every row since we're flipping the halves
    for (j=0; j<imageData.width/2; j++)
    {
       var index=(i*4)*imageData.width+(j*4);
       var mirrorIndex=((i+1)*4)*imageData.width-((j+1)*4);
       for (p=0; p<4; p++)
       {
         var temp=imageData.data[index+p];
         imageData.data[index+p]=imageData.data[mirrorIndex+p];
         imageData.data[mirrorIndex+p]=temp;
       }
    }
  }
  myCanvasContext.putImageData(imageData,0,0,0,0, imageData.width, imageData.height);
  return myCanvas.toDataURL();
}
[/c]

The flipping is done in the 3 loops above. The number 4 is there because every pixel consists of 3 bytes (for red, green, blue, and alpha). The return value is an img object. Additional guide: http://www.permadi.com/tutorial/jsCanvasGrayscale/index.html

To save Canvas image as files:
http://www.permadi.com/blog/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/

2 Responses to “HTML5: Using Canvas to Flip Images”

  1. [...] This post was mentioned on Twitter by Dharmveer Motyar. Dharmveer Motyar said: permadi.com – Blog " HTML5: Using Canvas to Flip Images http://ff.im/-jf2L6 [...]

  2. [...] http://www.permadi.com/blog/2009/04/html5-using-canvas-to-flip-images/   [...]