如何获取地图框上像素的颜色

时间:2019-09-09 23:43:55

标签: javascript canvas html5-canvas mapbox mapbox-gl-js

我的地图上有雷达栅格,我想通过光标的位置显示雷达的数据颜色。

An example of a radar

我正在尝试通过self.videoCamera.useAVCaptureVideoPreviewLayer = YES; 获取mapbox画布的上下文,但是它返回null。

有办法吗?

1 个答案:

答案 0 :(得分:2)

您可以通过这种方式获取画布上下文(webgl)并检查颜色。

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}`);
  }
});

我必须将地图选项preserveDrawingBuffer设置为true才能获得像素值。

const map = new mapboxgl.Map({
  container: "map",
  style: "mapbox://styles/mapbox/light-v10",
  zoom: 4,
  center: [77.209, 28.6139],
  preserveDrawingBuffer: true
});

此Codepen实现了一个简单的颜色检查器:https://codepen.io/manishraj/full/jONzpzL