How to read pixel values of an ImageOverlay in React-Leaflet by mousemove event?

60 Views Asked by At

I am trying to read pixel values of an ImageOverlay in React-Leaflet on every mousemove event. I want to use the canvas API to read pixel values and display the RGB value in a sticky tooltip. Can anyone provide guidance on how to achieve this? Thank you!


1

There are 1 best solutions below

0
On BEST ANSWER

Here is the solution:

const onMouseMove = (event) => {
  const canvas = document.createElement('canvas');
  canvas.style.display = 'none';
  const ctx = canvas.getContext('2d');
  const image = imageRef.current._image;
  const width = image.width;
  const height = image.height;
  const x = event.originalEvent.offsetX;
  const y = event.originalEvent.offsetY;
  image.crossOrigin = "Anonymous"; // Set the crossOrigin attribute of the image "Important"
  canvas.width = width;
  canvas.height = height;
  ctx.drawImage(image, 0, 0, width, height);
  const pixelData = ctx.getImageData(x, y, 1, 1).data;
  console.log(`%cPixel value at (${x}, ${y}): R=${pixelData[0]}, G=${pixelData[1]}, B=${pixelData[2]}, A=${pixelData[3]}`, `background-color: rgb(${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]})`);
  }

Image overlay component:

<ImageOverlay
  url={`path-to-image-address`}
  bounds={bound}
  ref={imageRef}
  interactive={true}
  eventHandlers={{
    mousemove: onMouseMove,
  }}
/>