Latest web development tutorials

HTML canvas getImageData () method

HTML canvas Reference Manual HTML canvas Reference Manual

Examples

The following code getImageData () Copy on canvas rectangle designated pixel data, and () the image data back into the canvas by 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"

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

Internet Explorer 9, Firefox, Opera, Chrome and Safari support getImageData () method.

Note: 8 and earlier nternet Explorer does not support the <canvas> element.


Definition and Usage

getImageData () method returns ImageData object that is a copy of the specified rectangular canvas pixel data.

Note: ImageData object is not the image, which provides a portion of the canvas (rectangle), and saved within the rectangle information of each pixel.

ImageData object for each pixel, there are four areas of information, namely 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 in the form of an array and stored in ImageData object data properties.

Tip: Complete array of color / alpha information in the operation, you can use putImageData () method of the image data is copied back to the canvas.

Example:

The following code can be obtained ImageData object is returned in the first pixel color / alpha information:

red=imgData.data[0];
green=imgData.data[1];
blue=imgData.data[2];
alpha=imgData.data[3];

try it

Tip: You can also use getImageData () method to reverse the color of each pixel of an image on the canvas.

Use this formula through all the pixels, and change its color values:

red=255-old_red;
green=255-old_green;
blue=255-old_blue;

Look at the following "try" instance!


JavaScript syntax

JavaScript syntax: context .getImageData (x, y, width, height);

Parameter Value

参数 描述
x 开始复制的左上角位置的 x 坐标(以像素计)。
y 开始复制的左上角位置的 y 坐标(以像素计)。
width 要复制的矩形区域的宽度。
height 要复制的矩形区域的高度。


Examples

More examples

The image you want to use:

The Scream

Examples

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

YourbrowserdoesnotsupporttheHTML5canvastag.

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.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"


HTML canvas Reference Manual HTML canvas Reference Manual