Maxim Shoustin
Maxim Shoustin

Reputation: 77930

How to color image pixel in JavaScript?

I'm looking for the way to color image pixel by some rule. Lets say I have some image:

<div id="static">
  <img border="0" src="some/image.png">
</div>

I want to color pixel to black based on RGB (or other way).

enter image description here

to

enter image description here

I know how to do that in Java

and found source how to do that on C++ (example)

but JavaScript ... hmmm

Please, help me.

Upvotes: 0

Views: 5384

Answers (1)

Benno
Benno

Reputation: 3008

You should be able to do something similar to this, albeit probably quite slowly using canvas.

See this post for how to grab the pixel colour after converting your image to a canvas representation: How to get a pixel's x,y coordinate color from an image?.

You would have to replace event.OffsetX and event.OffsetY with the coordinate of each individual pixel using a for loop to retrieve the RGB of each pixel. Then, if it doesn't match the blue's RGB values, replace the pixel colour with black, and if it is the blue, replace it with white.

It would be pretty damn slow, borderline probably not doable without locking up the browser (I haven't personally worked with canvas yet to know its performance), unless you offload it to a web worker so it happens in another thread.

Upvotes: 1

Related Questions