0

I have radar raster on my map and i want to show the data color of the radar by the position of the cursor.

An example of a radar

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?

phantomraa
  • 1,523
  • 1
  • 18
  • 25

1 Answers1

5

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

Manish
  • 4,525
  • 1
  • 26
  • 38
  • The codepen doesn't quite work... when I hover over the water, I get red/peach colors like the land. – colllin Dec 03 '19 at 22:24