HTML5 Canvas Reference - ImageData








ImageData object is used to represent the color data on canvas.

ImageData has three parts:

data
the pixel color data of the area stored in ImageData object
height
the height of the area stored in ImageData object
width
the width of the area stored in ImageData object

The data property contains image data of the specified ImageData object.

Every pixel in an ImageData object has four-element-array-like value, the RGBA values:

R
The color red from 0 to 255
G
The color green from 0 to 255
B
The color blue from 0 to 255
A
The alpha channel from 0 to 255. 0 is transparent and 255 is solid

The color information is stored in an array from the data property of the ImageData object.

Browser compatibility

width Yes Yes Yes Yes Yes

Example

The following code manipulate the ImageData object.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from w ww .  j  a v  a  2 s .co m-->
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var imgData = ctx.createImageData(100, 100);
    
    var i;
    for (i = 0; i < imgData.data.length; i += 4) {
        imgData.data[i+0] = 200;
        imgData.data[i+1] = 200;
        imgData.data[i+2] = 200;
        imgData.data[i+3] = 255;
    }
    
    ctx.putImageData(imgData, 10, 10);
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code manipulate the ImageData object.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from   w w  w. ja  v a 2s  . com-->
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var imgData = ctx.createImageData(100, 100);
    console.log("Height of imgData is: " + imgData.height);
    console.log("Width of imgData is: " + imgData.width);

</script>
</body>
</html>

The code above is rendered as follows: