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)
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)
Share Improve this question edited Feb 24, 2012 at 11:38 Oleg Mikheev 17.5k16 gold badges76 silver badges97 bronze badges asked Feb 24, 2012 at 11:20 user1004912user1004912 1061 silver badge7 bronze badges 5- What language do you want to use ? php ? – JuSchz Commented Feb 24, 2012 at 11:24
- This might be a good place to start: beej.us/blog/2010/02/html5s-canvas-part-ii-pixel-manipulation – Aaron Newton Commented Feb 24, 2012 at 11:45
- @julesanchez I didn't know you can use PHP to interact with HTML canvases. – JJJ Commented Feb 24, 2012 at 11:47
- @julesanchez I'm trying to this in HTML5 – user1004912 Commented Feb 24, 2012 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 Commented Feb 24, 2012 at 11:58
1 Answer
Reset to default 6You 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.