HTML canvas getImageData()Method
Examples
The following code copies the pixel data of a specified rectangle on the canvas using getImageData(), and then puts the image data back onto the canvas using putImageData():
Try it yourself »
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 that copies the pixel data of a specified rectangle on the canvas.
Note:The ImageData object is not an image; it specifies a part (rectangle) of the canvas and stores the information of each pixel within that rectangle.
For each pixel in the ImageData object, there are four pieces of information, namely the RGBA values:
R - Red (0-255)
G - Green (0-255)
B - Blue (0-255)
A - Alpha channel (0-255; 0 is transparent, 255 is fully visible)
The color/alpha information exists in array form and is stored in the ImageData object'sdataproperty.
Tip:After you have finished manipulating the color/alpha information in the array, you can use theputImageData()method to copy the image data back onto the canvas.
Example:
The following code can obtain the color/alpha information of the first pixel in the returned ImageData object:
green=imgData.data[1];
blue=imgData.data[2];
alpha=imgData.data[3];
Tip:You can also use the getImageData() method to invert the color of each pixel of an image on the canvas.
Use this formula to loop through all the pixels and change their color values:
green=255-old_green;
blue=255-old_blue;
See the "Try it yourself" example below!
JavaScript Syntax
| JavaScript syntax: | context.getImageData(x,y,width,height); |
|---|
Parameter Values
| Parameter | Description |
|---|---|
| x | The x-coordinate (in pixels) of the upper-left corner position where copying starts. |
| y | The y-coordinate (in pixels) of the upper-left corner position where copying starts. |
| width | The width of the rectangular area to be copied. |
| height | The height of the rectangular area to be copied. |

More Examples
Image to use:

Example
Use getImageData() to invert the color of each pixel of the image on the canvas:
JavaScript:
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,0,0);
var imgData=ctx.getImageData(0,0,c.width,c.height);
// invert colors
for (var i=0;i<imgData.data.length;i+=4)
{
imgData.data[i]=255-imgData.data[i];
imgData.data[i+1]=255-imgData.data[i+1];
imgData.data[i+2]=255-imgData.data[i+2];
imgData.data[i+3]=255;
}
ctx.putImageData(imgData,0,0);
Try it yourself »
HTML canvas Reference Other Extensions