I have radar raster on my map and i want to show the data color of the radar by the position of the cursor.
I'm trying to get context of a mapbox canvas by map.getCanvas().getContext('2d') but it returns null.
Is there a way to do that?
I have radar raster on my map and i want to show the data color of the radar by the position of the cursor.
I'm trying to get context of a mapbox canvas by map.getCanvas().getContext('2d') but it returns null.
Is there a way to do that?
You can obtain the canvas context (webgl) this way and inspect colors.
map.on("mousemove", e => {
const canvas = map.getCanvas();
const gl = canvas.getContext('webgl') || canvas.getContext('webgl2');
if (gl) {
const { point } = e;
const { x, y } = point;
const data = new Uint8Array(4);
const canvasX = x - canvas.offsetLeft;
const canvasY = canvas.height - y - canvas.offsetTop;
gl.readPixels(canvasX, canvasY, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, data);
const [r, g, b, a] = data;
const color = `rgba(${r}, ${g}, ${b}, ${a})`;
console.log(`Color at (${x}, ${y}) = ${color}`);
}
});
I had to set map option preserveDrawingBuffer to true to be able to get pixel values.
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/light-v10",
zoom: 4,
center: [77.209, 28.6139],
preserveDrawingBuffer: true
});
This codepen implements a simple color inspector: https://codepen.io/manishraj/full/jONzpzL