Canvas getImageData() Method
Definition and Usage
getImageData()
The method returns an ImageData object that copies the pixel data of the specified rectangle on the canvas.
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 exists as an array and is stored in the ImageData object's data property.
Tip:After operating on the color/alpha information in the array, you can use putImageData() The method copies 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:
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 colors of each pixel on a canvas image.
Use this formula to iterate over all pixels and change their color values:
red=255-old_red; green=255-old_green; blue=255-old_blue;
(See the 'Try It Yourself' example below.)
Example
Example 1
The following code copies the pixel data of the specified rectangle on the canvas using getImageData(), and then puts the image data back onto the canvas using putImageData():
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.fillStyle = "red"; ctx.fillRect(10, 10, 50, 50); function copy() { var imgData = ctx.getImageData(10, 10, 50, 50); ctx.putImageData(imgData, 10, 70); }
Tip:More examples are provided at the bottom of the page.
Syntax
var imgData = context.getImageData(x,y,width,height);
Parameter value
Parameters | Description |
---|---|
x | The x coordinate of the top-left corner of the starting position of the copy. |
y | The y coordinate of the top-left corner of the starting position of the copy. |
width | The width of the rectangular area to be copied. |
height | The height of the rectangular area to be copied. |
More examples
Example 2
Image to be used:

Use getImageData() to reverse the color of each pixel on the canvas.
JavaScript:
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var img = document.getElementById("tulip"); ctx.drawImage(img, 0, 0); var imgData=ctx.getImageData(0, 0, c.width, c.height); // Reverse 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);
Browser support
The numbers in the table indicate the version of the browser that fully supports this attribute.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
4.0 | 9.0 | 3.6 | 4.0 | 10.1 |
Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.