How to get pixel color from canvas, on mouse move with JavaScript?

Spread the love

To get pixel color from canvas, on mousemove with JavaScript, we use the getImageData method.

For instance, we write

<canvas
  id="myCanvas"
  width="400"
  height="250"
  style="background: red"
  onmouseover="echoColor(event)"
>
</canvas>

to add a canvas.

We set the mouseovef event listener to the echoColor function.

Then we write

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(10, 10, 50, 50);

function echoColor(e) {
  const imgData = ctx.getImageData(e.pageX, e.pageY, 1, 1);
  const [red, green, blue, alpha] = imgData;
  console.log(red, green, blue, alpha);
}

to define the echoColor function that gets the pixel at the mouse position with getImageData called with the x and y coordinates of the mouse pointer.

We get the canvas with getElementById.

And we get the canvas context with getContext.

Then we get the rgba values from the imgData array.

Leave a Reply

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