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.
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.
Here's what you have to do:
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