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:
getImageData() |
Yes | Yes | Yes | Yes | Yes |
context.getImageData(x,y,width,height);
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 |
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:
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: