HTML canvas createImageData () method
Examples
Create a 100 * 100 pixels ImageData object in which each pixel is red, 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"
Browser Support
Internet Explorer 9, Firefox, Opera, Chrome and Safari support createImageData () method.
Note: 8 and earlier versions of Internet Explorer do not support the <canvas> element.
Definition and Usage
createImageData () method creates a new blank ImageData object. The default value of the new object pixel transparent black.
ImageData object for each pixel, there are four areas 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)
Thus, transparent black representation (0,0,0,0).
color / alpha information in the form of an array, and since the array contains four pieces of information for each pixel, so the size of the array is ImageData object four times: width * height * 4. (Array size obtained a more simple way is to use ImageDataObject.data.length)
It contains color / alpha ImageData array information stored in the object's data property.
Tip: Complete array of color / alpha information in the operation, you can use putImageData () method of the image data is copied back to the canvas.
Example:
The ImageData object first pixel to red syntax:
imgData.data[0]=255;
imgData.data[1]=0;
imgData.data[2]=0;
imgData.data[3]=255;
The object ImageData second pixel turns green syntax:
imgData.data[4]=0;
imgData.data[5]=255;
imgData.data[6]=0;
imgData.data[7]=255;
JavaScript syntax
There are two versions of createImageData () method:
1. specify the size (in pixels) to create a new ImageData objects:
JavaScript syntax: | var imgData = context .createImageData (width,height); |
---|
2. Create the same as another object size ImageData new ImageData specified object (image data will not be copied):
JavaScript syntax: | var imgData = context .createImageData (imageData); |
---|
Parameter Value
参数 | 描述 |
---|---|
width | ImageData 对象的宽度,以像素计。 |
height | ImageData 对象的高度,以像素计。 |
imageData | 另一个 ImageData 对象。 |
HTML canvas Reference Manual