如何获取地图框上像素的颜色 [英] How to get the color of pixels on mapbox
问题描述
我的地图上有雷达栅格,我想通过光标的位置显示雷达的数据颜色.
I have radar raster on my map and i want to show the data color of the radar by the position of the cursor.
我正在尝试通过 map.getCanvas().getContext('2d')
获取mapbox画布的上下文,但是它返回null.
I'm trying to get context of a mapbox canvas by map.getCanvas().getContext('2d')
but it returns null.
有办法吗?
推荐答案
您可以通过这种方式获取画布上下文(webgl)并检查颜色.
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}`);
}
});
我必须将地图选项 preserveDrawingBuffer
设置为 true
才能获得像素值.
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
});
此Codepen实现了一个简单的颜色检查器: https://codepen.io/manishraj/full/jONzpzL
This codepen implements a simple color inspector: https://codepen.io/manishraj/full/jONzpzL
这篇关于如何获取地图框上像素的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!