Search

4/28/2009

canvas Pixel-based manipulation: getImageData & putImageData

Pixel-based manipulation
The 2D Context API provides you with three methods that help you draw pixel-by-pixel: createImageData, getImageData, and putImageData.

Raw pixels are held in objects of type ImageData. Each object has three properties: width, height and data. The data property is of type CanvasPixelArray, holding a number of elements equal to width*height*4; this means that for every pixel you define the red, green, blue and alpha values of all the pixels, in the order you want them to appear (all the values range from 0 to 255, including alpha!). Pixels are ordered left to right, row by row, from top to bottom.


// Create an ImageData object.
var imgd = context.createImageData(50,50);
var pix = imgd.data;

// Loop over each pixel and set a transparent red.
for (var i = 0; n = pix.length, i < n; i += 4) {
pix[i ] = 255; // red channel
pix[i+3] = 127; // alpha channel
}

// Draw the ImageData object at the given (x,y) coordinates.
context.putImageData(imgd, 0,0);

http://chunghe.googlecode.com/svn/trunk/project/canvas-image-manipulation/gray.htm

沒有留言: