Pixel Manipulation

The canvas context provides direct access to the pixel data of the drawing area. Read and write individual red, green, blue, and alpha values to create custom image filters and effects.

The ImageData Object

Pixel manipulation centers around the ImageData object, which stores the underlying pixel data for a rectangle of a canvas area.

Method Description
getImageData(sx, sy, sw, sh) Returns an ImageData object representing the pixel data for the specified rectangle.
putImageData(imagedata, dx, dy) Paints data from the specified ImageData object back onto the canvas.
createImageData(width, height) Creates a new, blank ImageData object with the specified dimensions (all pixels are transparent black).

Pixel Representation

The data property of an ImageData object is a one-dimensional array containing the data in the RGBA order, with integer values between 0 and 255 (inclusive). Each pixel is represented by four values in the array (Red, Green, Blue, and Alpha).

To access an individual pixel's values, loop through the array in steps of four:

Pixel Manipulation Example

The following example loads an image and then uses getImageData() and putImageData() to invert its colors when the button is clicked:

View Output

Security and Origin

For security reasons, browsers only allow you to call getImageData() if the canvas has not been "tainted" by drawing images from a different domain without proper CORS clearance.

The next lesson explains how to implement hit detection to make your drawings interactive.