Get the color of an area or specific coordinate of a PNG image or JPG when clicking

4

I need to get the color of an image in an exact coordinate where the user clicks, I need this to be possible with png, jpg or svg format images.

    
asked by Jcastillovnz 17.10.2018 в 17:46
source

1 answer

7

Here's what you have to do:

  • create a canvas
  • calculate the relative coordinates of the click on the image
  • get the corresponding pixel from the canvas

I'll give you an example:

const gatete= document.getElementById('gato');
const output= document.getElementById('output');

gatete.addEventListener('click', function (e) {
  let ctx;
  if(!this.canvas) {
      this.canvas = document.createElement('canvas');
      this.canvas.width = this.width;
      this.canvas.height = this.height;
      ctx=this.canvas.getContext('2d');
      ctx.drawImage(this, 0, 0, this.width, this.height);
  } else {
    ctx=this.canvas.getContext('2d');
  }
  const pixel = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data;
        
  output.innerHTML ='R: ' + pixel[0] + '<br>G: ' + pixel[1] +
      '<br>B: ' + pixel[2] + '<br>A: ' + pixel[3];
                
});
img,pre {
display: inline-block;
}
<img id="gato" src="http://placekitten.com/300/200" crossorigin="anonymous">

<pre id="output"></pre>

I've done it with pure JS, as you can see the code is not very complicated once you know what to achieve

    
answered by 17.10.2018 в 19:18