Sometimes, we want to get pixel color from an image with JavaScript.
In this article, we’ll look at how to get pixel color from an image with JavaScript.
How to get pixel color from an image with JavaScript?
To get pixel color from an image with JavaScript, we can put the image in the canvas.
For instance, we write:
const myImg = new Image();
myImg.crossOrigin = "Anonymous";
myImg.onload = () => {
const context = document.createElement('canvas').getContext('2d');
context.drawImage(myImg, 0, 0);
const {
data
} = context.getImageData(10, 10, 1, 1);
console.log(data)
}
myImg.src = 'https://picsum.photos/200/300';
In myImg.onload
we get the pixel data from the canvas by creating a canvas element with createElement
.
Then we get the context with getContext
.
Next, we call drawImage
to draw the image.
And then we call getImageData
with the x, y coordinates of the pixel to get as the first 2 arguments.
As a result, we see that data
is a Uint8ClampedArray
.
Conclusion
To get pixel color from an image with JavaScript, we can put the image in the canvas.
2 replies on “How to get pixel color from an image with JavaScript?”
where is demo?
I like its short article but it feels incomplete explanation.