Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML canvas ImageData data attribute

HTML canvas ImageData data attribute

Canvas Object Reference Canvas object

Example

Create an ImageData object of 100*100 pixels, where each pixel is 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[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 the ImageData data attribute.

**Note:** Internet Explorer 8 and earlier versions do not support .


Definition and Usage

The data attribute returns 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)

The color/alpha information is stored as an array in the data attribute of the ImageData object.

Example:

The syntax to turn the first pixel in the ImageData object red:

imgData=ctx.createImageData(100,100);

imgData.data[0]=255;

imgData.data[1]=0;

imgData.data[2]=0;

imgData.data[3]=255;

The syntax to turn the second pixel in the ImageData object green:

imgData=ctx.createImageData(100,100);

imgData.data[4]=0;

imgData.data[5]=255;

imgData.data[6]=0;

imgData.data[7]=255;

**Tip:** See the createImageData(), getImageData() and putImageData() method, for more information about the ImageData object.


JavaScript syntax

JavaScript syntax: imageData.data;

Canvas Object Reference Canvas object