HTML 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)

The color/alpha exists in array form 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 can obtain 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];

Try It Yourself

Tip:You can also use the getImageData() method to reverse the color of each 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 Yourself" example below.)

Instance

Example 1

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():

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);
}

Try It Yourself

Tip:More examples are provided at the bottom of the page.

Syntax

var imgData=context.getImageData(x,y,width,height);

Parameter value

Parameter Description
x The x coordinate of the top-left corner of the starting copy position.
y The y coordinate of the top-left corner of the starting copy position.
width The width of the rectangular area to be copied.
height The height of the rectangular area to be copied.

More examples

Example 2

The image to be used:

The Tulip

Use getImageData() to reverse the color of each pixel on the canvas.

Your browser does not support the HTML5 canvas tag.

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);

Try It Yourself

Browser Support

The numbers in the table indicate the first browser version 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.