HTML5 Canvas Reference - getImageData()








The getImageData() function returns retrieve a set of pixel data from the canvas.

The ImageData object represents a rectangle area of information and holds every pixel inside that rectangle.

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

Browser compatibility

getImageData() Yes Yes Yes Yes Yes

JavaScript Syntax

context.getImageData(x,y,width,height);




Parameter Values

Parameter Description
x The x coordinate (in pixels) of the upper-left corner to start copy from
y The y coordinate (in pixels) of the upper-left corner to start copy from
width The width of the rectangular area you will copy
height The height of the rectangular area you will copy

Example

The following code copies ImageData.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
    var canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d");
    canvas.width = canvas.height = 400;<!--from w  w  w.  j a  va2s  .  c  o m-->
    ctx.fillStyle = "red";
    ctx.fillRect(0,0,50,50);
    ctx.fillStyle = "blue";
    ctx.fillRect(10,10,30,30);
    var imageData = ctx.getImageData(0,0,50,50);
    ctx.putImageData(imageData,50,50,10,10,40,40);
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code inverts the color in ImageData object.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(0,0,50,50);<!--from w w  w .  j a  v a  2s. c  om-->
    ctx.fillStyle = "blue";
    ctx.fillRect(10,10,30,30);
    
    var imgData = ctx.getImageData(0, 0, c.width, c.height);
    // invert colors
    var i;
    for (i = 0; i < imgData.data.length; i += 4) {
        imgData.data[i] = 255 - imgData.data[i];
        imgData.data[i+1] = 255 - imgData.data[i+1];
        imgData.data[i+2] = 255 - imgData.data[i+2];
        imgData.data[i+3] = 255;
    }
    ctx.putImageData(imgData, 50,50,10,10,40,40);
</script>
</body>
</html>

The code above is rendered as follows: