javascript - 如何获取mapbox上像素的颜色

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

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

An example of a radar

我试图通过 map.getCanvas().getContext('2d') 获取 Mapbox Canvas 的上下文,但它返回 null。

有办法做到这一点吗?

最佳答案

您可以通过这种方式获取 Canvas 上下文(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}`);
  }
});

我必须将 map 选项 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

关于javascript - 如何获取mapbox上像素的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862383/

相关文章:

javascript - Jasmine - 如何监视函数内的函数调用?

javascript - 单击模态自动播放 Vimeo 视频

javascript - 在每次移动鼠标时,可拖动元素的定位都会重置为零

javascript - 使用compressor.js使用图像作为水印

javascript - 使用 JavaScript(可能是 CSS)在特定宽度/高度的 HTML5 Canvas 中显示完整图像尺寸(100% 宽度/高度)

html - 解释 HTML5 Canvas 元素的优秀截屏视频源

javascript - webpack 4.1.1 -> configuration.module 有一个未知的属性 'loaders' 。

javascript - 我可以重新使用 html5 canvas 元素的转换吗?

javascript - 引用错误: Point is not defined

javascript - 在 JavaScript 函数中加载图像