Is it possible to read pixels of an image in canvas A and create pixels on canvas B? And I want to create the new pixels on Canvas B only where the image's pixels are green. eg. If images' pixel (120,45) is green I need to create a green colored pixel in Canvas B at (120,45)
-
What language do you want to use ? php ? – JuSchz Feb 24 '12 at 11:24
-
This might be a good place to start: http://beej.us/blog/2010/02/html5s-canvas-part-ii-pixel-manipulation/ – Aaron Newton Feb 24 '12 at 11:45
-
@julesanchez I didn't know you can use PHP to interact with HTML canvases. – JJJ Feb 24 '12 at 11:47
-
@julesanchez I'm trying to this in HTML5 – user1004912 Feb 24 '12 at 11:56
-
@AaronNewton Thanks for the link. I've already tried pixel manipulation to invert an image. Just wanted to know whether I can create specific colored pixels of an Image at the same x,y coordinates in another canvas. – user1004912 Feb 24 '12 at 11:58
1 Answers
You can use canvas ImageData to get color values for each pixels. The function:
context.getImageData(left, top, width, height);
returns an ImageData object, which consists of the following properties:
- width
- height
- data (CanvasPixelArray)
The CanvasPixelArray
contains the RGBA values for all the pixels, starting from top-left working its way to bottom-right. So in other words, it is an array containing 4*width*height
number of entries.
Using that, you can start looping through each pixel (+=4
entries per pixel), and check the RGBA values. If they match a specific value you want, i.e. green, then you would copy that value to a canvas B, which you would create by modifying a newly created ImageData object.
You can create a new empty ImageData object with:
context.createImageData(cssWidth, cssHeight)
Note that you will need to know specific RGBA values that identify "green" or define specific conditions, i.e. if the G value of RGBA is >= 150
then it is "green".
Also note that you cannot get the ImageData
that has been tainted resources outside of your origin. i.e., if you draw an image onto the canvas that isn't CORS safe, you won't be able to retrieve the ImageData
from that canvas anymore, much like how you can't use toDataURL
either.
-
Thanks. I've tried the `getImageData()` and `putImageData()` to invert an image and thought this might be the correct way. But I'm not sure if the pixels would be created at the same x,y coordinates in the canvas B, as in the image. – user1004912 Feb 24 '12 at 12:06
-
@user1004912 If you specify the same dimensions and place the newly created ImageData object into the same position you extracted the initial one from, then their dimensions/position will be exactly the same. – Niklas Feb 24 '12 at 12:08