How to get a pixel from HTML canvas with JavaScript?

Spread the love

Sometimes, we want to get a pixel from HTML canvas with JavaScript.

In this article, we’ll look at how to get a pixel from HTML canvas with JavaScript.

How to get a pixel from HTML canvas with JavaScript?

To get a pixel from HTML canvas with JavaScript, we call the getImageData method.

For instance, we write

const context = document.getElementById("myCanvas").getContext("2d");
const imgd = context.getImageData(x, y, width, height);
const pix = imgd.data;

for (let i = 0; i < pix.length; i += 4) {
  pix[i] = 255 - pix[i];
  pix[i + 1] = 255 - pix[i + 1];
  pix[i + 2] = 255 - pix[i + 2];
}

context.putImageData(imgd, x, y);

to get the canvas context with getContext.

Then we get the pixel data at coordinates x, y with context.getImageData(x, y, width, height).

We get the pixel from with x, y as the top left corner and extend to the width and height.

Then we invert the colors with the for loop.

pix[i] = 255 - pix[i]; inverts red.

pix[i + 1] = 255 - pix[i + 1] inverts green.

pix[i + 2] = 255 - pix[i + 2]; inverts blue.

Conclusion

To get a pixel from HTML canvas with JavaScript, we call the getImageData method.

Leave a Reply

Your email address will not be published. Required fields are marked *