HTML canvas getImageData()
Method
Example
The following code copies the pixel data of a specified rectangle on the canvas using getImageData()
, and then places the image data back onto the canvas using putImageData()
:
Browser Support
Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the getImageData()
method.
Note: Internet Explorer 8 and earlier versions do not support the <canvas>
element.
Definition and Usage
The getImageData()
method returns an ImageData object, which copies the pixel data of the specified rectangle on the canvas.
Note: The ImageData object is not an image; it specifies a part (rectangle) of the canvas and stores information about each pixel within that rectangle.
For each pixel in the ImageData object, there are four pieces of information, namely RGBA values:
R - Red (0-255)
The color/alpha information is stored in an array and is contained in the data property of the ImageData object.
Tip: After manipulating the color/alpha information in the array, you can use the putImageData() method to copy the image data back onto the canvas.
Example:
The following code retrieves the color/alpha information of the first pixel in the returned ImageData object:
Tip: You can also use the getImageData()
method to invert the color of each pixel in an image on the canvas.
Traverse all pixels using this formula and change their color values:
See the "Try it" example below!
JavaScript Syntax
| JavaScript Syntax: | context.getImageData(x, y, width, height); | | --- | --- |
Parameter Values
Parameter | Description |
---|---|
x | The x coordinate of the upper-left corner where copying starts (in pixels). |
y | The y coordinate of the upper-left corner where copying starts (in pixels). |
width | The width of the rectangle area to be copied. |
height | The height of the rectangle area to be copied. |
More Examples
Image to Use:
Example
Use getImageData()
to invert the color of each pixel in an image on the canvas:
JavaScript: