Canvas createImageData() method
Definition and usage
createImageData()
Method to create 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 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).
color/alpha exists in array form, and since the array contains four pieces of information for each pixel, the size of the array is four times the size of the ImageData object. (There is a simpler way to get the size of the array, which is to use ImageDataObject.data.length)
The array containing color/alpha information is stored in the data properties.
Tip:After the color/alpha information in the array is processed, you can use putImageData() The method copies the image data back to the canvas.
Example:
This syntax changes 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;
This syntax changes the second pixel of the ImageData object to red:
imgData=ctx.createImageData(100,100); imgData.data[4]=0; imgData.data[5]=255; imgData.data[6]=0; imgData.data[7]=255;
Example
Create an ImageData object of 100*100 pixels, where each pixel is red, and then put it on the canvas:
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);
Syntax
There are two versions of the createImageData() method:
1. Create a new ImageData object with the specified size (in pixels):
var imgData=context.createImageData(width,height);
2. Create a new ImageData object with the same size as the specified another ImageData object (the image data will not be copied):
var imgData=context.createImageData(imageData);
Parameter value
Parameter | Description |
---|---|
width | The width of the ImageData object, in pixels. |
height | The height of the ImageData object, in pixels. |
imageData | Another ImageData object. |
Browser Support
The numbers in the table indicate the first browser version that 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.