Latest web development tutorials

HTML canvas ImageData data attribute

HTML canvas Reference Manual HTML canvas Reference Manual

Examples

Create a 100 * 100 pixels ImageData objects, where each pixel are set to red:

canvas

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var imgData=ctx.createImageData(100,100);
for (var i=0;i<imgData.data.length;i+=4)
{
imgData.data[i+0]=255;
imgData.data[i+1]=0;
imgData.data[i+2]=0;
imgData.data[i+3]=255;
}
ctx.putImageData(imgData,10,10);

try it"

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

Internet Explorer 9, Firefox, Opera, Chrome and Safari support ImageData data attributes.

Note: 8 and earlier versions of Internet Explorer do not support the <canvas> element.


Definition and Usage

data property returns an object that contains the image data specified ImageData object.

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 the data attribute ImageData object.

Example:

The ImageData object first pixel to red syntax:

imgData=ctx.createImageData(100,100);

imgData.data[0]=255;
imgData.data[1]=0;
imgData.data[2]=0;
imgData.data[3]=255;

The object ImageData second pixel turns green syntax:

imgData=ctx.createImageData(100,100);

imgData.data[4]=0;
imgData.data[5]=255;
imgData.data[6]=0;
imgData.data[7]=255;

Tip: See createImageData () , getImageData () and putImageData () method to get more knowledge about ImageData object.


JavaScript syntax

JavaScript syntax: imageData .data;


HTML canvas Reference Manual HTML canvas Reference Manual