HTML canvas createImageData()Method
Examples
Create a 100*100 pixel ImageData object in which every pixel is red, and then put it on the canvas:
JavaScript:
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 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 exists 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 represents (0,0,0,0).
The color/alpha information exists as 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 obtain the array size, which is to use ImageDataObject.data.length)
The array containing 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 onto the canvas.
Example:
The syntax to turn the first pixel in the ImageData object red:
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.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 (without copying the 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. |
HTML canvas Reference Manual Other Extensions