我试图在每个鼠标移动事件上读取 React-Leaflet 中 ImageOverlay 的像素值。我想使用 canvas API 读取像素值并在粘性工具提示中显示 RGB 值。任何人都可以提供有关如何实现这一目标的指导吗?谢谢!
解决方案如下:
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]})`);
}
图像叠加组件:
<ImageOverlay
url={`path-to-image-address`}
bounds={bound}
ref={imageRef}
interactive={true}
eventHandlers={{
mousemove: onMouseMove,
}}
/>