Sul*_*aei 2 javascript canvas html5-canvas mapbox mapbox-gl-js
我的地图上有雷达光栅,我想通过光标的位置显示雷达的数据颜色。
我试图获取 Mapbox 画布的上下文,map.getCanvas().getContext('2d')但它返回 null。
有没有办法做到这一点?
您可以通过这种方式获取画布上下文 (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}`);
}
});
Run Code Online (Sandbox Code Playgroud)
我必须设置地图选项preserveDrawingBuffer才能true获取像素值。
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/light-v10",
zoom: 4,
center: [77.209, 28.6139],
preserveDrawingBuffer: true
});
Run Code Online (Sandbox Code Playgroud)
这个codepen实现了一个简单的颜色检查器:https ://codepen.io/manishraj/full/jONzpzL
| 归档时间: |
|
| 查看次数: |
1604 次 |
| 最近记录: |