Home > front end >  How can I get the pixel color value of an image in javascript?
How can I get the pixel color value of an image in javascript?

Time:02-10

How can I get the pixel color value of an image in javascript?

I have an image like this: enter image description here

enter image description here

Click on the image to create a red circle.

so that a red circle is created in the forest, I don't want the red circle to be created outside the forest.

For this, I want to compare the backgroundcolor and the background value of the red circle created by clicking.

I am wondering how can I get the pixel color value of the clicked image.

CodePudding user response:

There is a whole section on HTML spec for image manipulation. https://html.spec.whatwg.org/#pixel-manipulation

But concretely, one possibility is to use the getImageData function : https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas#getting_the_pixel_data_for_a_context

This article helped me a lot for this kind of thing : https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/

Here my example of a basic implementation (I'm using Typescript for make it simpler):

function GetColorPixel(
  context: CanvasRenderingContext2D,
  x: number,
  y: number
): Array<number> {
  const imageData: Uint8ClampedArray = context.getImageData(x, y, 1, 1).data
  const rgbColor: Array<number> = [imageData[0], imageData[1], imageData[2]]
  return rgbColor
}

In this function, you need to pass the context of canvas for example

  •  Tags:  
  • Related