English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The read-only ImageData.data attribute returns Uint8ClampedArray, which describes a one-dimensional array containing data in RGBA order, using 0 to 255(including) integer representation.
Create a100 * 100-pixel ImageData object, where each pixel is set to red:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML canvas imgData.data attribute usage-Basic Tutorial(oldtoolbag.com)</<title> </<head> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3> Your browser does not support HTML5 canvas tag. </canvas> <script> 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); </script> </body> </html>Test and see ‹/›
IEFirefoxOperaChromeSafari
Internet Explorer 9and Firefox, Opera, Chrome, and Safari support ImageData data attribute.
Note:Internet Explorer 8 Prior versions do not support the <canvas> element.
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 completely visible)
color/alpha information exists in array form and is stored in the data attribute of the ImageData object.
Example:
Syntax to change 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;
Syntax to change the second pixel of the ImageData object to green:
imgData=ctx.createImageData(100,100); imgData.data[4]=0; imgData.data[5]=255; imgData.data[6]=0; imgData.data[7]=255;
Tip:See createImageData(),getImageData() andputImageData() methods to learn more about the ImageData object.
JavaScript syntax: | imageData.data; |
---|