The following code copies the pixel data for the specified rectangle on the canvas through Getimagedata (), and then puts the image data back into the canvas via Putimagedata ():
imgData=ctx.getImageData(10,10,50,50); Ctx.putimagedata (imgdata,10,70);}
Try it yourself.
Browser support
Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the Getimagedata () method.
Note: Internet Explorer 8 or earlier browsers do not support the <canvas> element.
Definition and usage
The Getimagedata () method returns a ImageData object that copies the pixel data of the canvas's specified rectangle.
For each pixel in the ImageData object, there is a four-part message, the RGBA value:
- 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 exists as an array and is stored in the Data property of the ImageData object.
Tip: After you have completed the Color/alpha information in the array, you can use the Putimagedata () method to copy the image data back to the canvas.
Example:
The following code obtains the Color/alpha information for the first pixel in the returned ImageData object:
RED=IMGDATA.DATA[0];GREEN=IMGDATA.DATA[1];BLUE=IMGDATA.DATA[2];ALPHA=IMGDATA.DATA[3];
Try it yourself.
Tip: You can also use the Getimagedata () method to invert the color of each pixel of an image on the canvas.
Use this formula to traverse all the pixels and change their color values:
Red=255-old_red;green=255-old_green;blue=255-old_blue;
(See the "Try it Yourself" example below.) )
JavaScript syntax
var imgdata=context.getimagedata (x,y,width,height);
Parameter values
| Parameters |
Description |
| X |
The x-coordinate at which to begin copying the upper-left position. |
| Y |
The y-coordinate at which to begin copying the upper-left position. |
| Width |
The width of the rectangular area that will be copied. |
| Height |
The height of the rectangular area to copy. |
More examples
Image to use:
Use Getimagedata () to invert the color of each pixel of an image on the canvas.
Javascript:
var C=document.getelementbyid ("MyCanvas"), Var ctx=c.getcontext ("2d"), Var Img=document.getelementbyid ("Tulip"); Ctx.drawimage (img,0,0); var imgdata= ctx.getImageData(0,0,c.width,c.height) ; Invert color for (Var i=0;i
Try it yourself.
HTML5 Canvas Getimagedata () method