0

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 Answer 1

1

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,
  }}
/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.