HTML5: Using Canvas to Flip Images
April 16, 2009

This example uses Canvas to flip an image.  For introduction to Canvas, please see

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.

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;
 //  alert(imgWidth);
  // 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++)
  myCanvasContext.putImageData(imageData,0,0,0,0, imageData.width, imageData.height);
  return myCanvas.toDataURL();

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:

To save Canvas image as files: