Canvas data attribute

Definition and Usage

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

For each pixel in the ImageData object, there are four types 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 data in the attribute.

Example:

Syntax to set the first pixel of the ImageData object to red:

imgData=ctx.createImageData(100,100);
imgData.data[0]=255;
imgData.data[1]=0;
imgData.data[2]=0;
imgData.data[3]=255;

Syntax to set the second pixel of the ImageData object to green:

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() Methods to learn more about the ImageData object.

Example

Create an ImageData object of 100*100 pixels, with each pixel set to red:

Your browser does not support the canvas tag.

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 yourself

Syntax

imageData.data;

Browser Support

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