HTML canvas getImageData() method
Example
The following code copies the pixel data of a specified rectangle on the canvas via getImageData(), then puts the image data back onto the canvas via putImageData():
const
canvas
=
document
.
getElementById
(
"
myCanvas
"
)
;
const
ctx
=
canvas
.
getContext
(
"
2d
"
)
;
ctx
.
fillStyle
=
"
red
"
;
ctx
.
fillRect
(
10
,
10
,
50
,
50
)
;
function
copy
(
)
{
const
imgData
=
ctx
.
getImageData
(
10
,
10
,
50
,
50
)
;
ctx
.
putImageData
(
imgData
,
10
,
70
)
;
}
Try it »
Browser support





Internet Explorer 9, Firefox, Opera, Chrome and Safari support the getImageData() method.
Note: Internet Explorer 8 and earlier versions do not support
Definition and Usage
The getImageData() method returns an ImageData object that copies the pixel data of the specified rectangle on the canvas.
**Note:** The ImageData object is not an image; it defines a region (rectangle) on 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)
color/alpha information is stored as an array and is kept in the ImageData object's data attribute.
**Tip:** After you finish manipulating the color/alpha information in the array, you can use putImageData() method to copy the image data back onto the canvas.
Example:
The following code obtains the color/alpha information of the first pixel in the returned ImageData object:
red=imgData.data[0];
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 every pixel of an image on the canvas.
Use this formula to iterate through all pixels and change their color values:
red=255-old_red;
green=255-old_green;
blue=255-old_blue;
See the "Try it" example below!
JavaScript syntax
| JavaScript syntax: | context.getImageData(x,y,width,height); |
|---|
Parameter value
| Parameters | Description |
|---|---|
| x | The x-coordinate (in pixels) of the upper-left position where copying starts. |
| y | The y-coordinate (in pixels) of the upper-left position where copying starts. |
| width | The width of the rectangular region to copy. |
| height | The height of the rectangular region to copy. |
More examples
The image to use:

Example
Use getImageData() to invert the color of every pixel of the image on the canvas:
JavaScript:
var c=document.getElementById("myCanvas");
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[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 »
HTML canvas Reference Manual