HTML5: Using Canvas to Flip Images
April 16, 2009
0
This example uses Canvas to flip an image. For introduction to Canvas, please see https://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.
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();
}
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: https://www.permadi.com/tutorial/jsCanvasGrayscale/index.html
To save Canvas image as files:
https://www.permadi.com/blog/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/