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
Share
You can use canvas ImageData to get color values for each pixels. The function:
returns an ImageData object, which consists of the following properties:
The
CanvasPixelArraycontains 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 containing4*width*heightnumber of entries.Using that, you can start looping through each pixel (
+=4entries 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:
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
>= 150then it is “green”.Also note that you cannot get the
ImageDatathat 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 theImageDatafrom that canvas anymore, much like how you can’t usetoDataURLeither.