HTML canvas data attribute

Definition and usage

data Properties return an object that contains the image data of the specified ImageData object.

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 exist as an array and are stored in the data Properties.

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, for more information about the ImageData object.

Instance

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 first browser version that fully supports this property.

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.