HTML canvas createImageData()Method

Canvas 对象参考手册Canvas Object

Example

Create a 100*100 pixel ImageData object where every pixel is red, and then put it on the 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 yourself »

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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

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


Definition and Usage

The createImageData() method creates a new blank ImageData object. The default pixel value of the new object is transparent black.

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)

Therefore, transparent black means (0,0,0,0).

The color/alpha information is stored in an array, and since the array contains four pieces of information for each pixel, the size of the array is four times that of the ImageData object: width*height*4. (There is a simpler way to get the array size, which is to use ImageDataObject.data.length)

The array containing the color/alpha information is stored in the ImageData object'sdataproperty.

Tip:After you have finished manipulating the color/alpha information in the array, you can use theputImageData()method to copy the image data back to the canvas.

Example:

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;

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;


JavaScript Syntax

There are two versions of the createImageData() method:

1. Create a new ImageData object with the specified dimensions (in pixels):

JavaScript syntax: var imgData=context.createImageData(width,height);

2. Create a new ImageData object with the same dimensions as another specified ImageData object (does not copy image data):

JavaScript syntax: var imgData=context.createImageData(imageData);

Parameter Values

Parameter Description
width The width of the ImageData object, in pixels.
height The height of the ImageData object, in pixels.
imageData Another ImageData object.


Canvas 对象参考手册Canvas Object

Other Extensions