akshat jain
akshat jain

Reputation: 27

How to find the rgb color of pixel under mouse hover in MapboxGL Js?

I would like to get the exact color in rgb of the pixel under mouse hover in MapboxGL Js. What can be the best possible way to get this done ?

Upvotes: 1

Views: 1265

Answers (1)

Adriana Babakanian
Adriana Babakanian

Reputation: 1299

To retrieve the RGB color of the pixel being hovered over in a Mapbox GL JS map, you can get the WebGL canvas context and use the WebGLRenderingContext.readPixels method to obtain each of the four RGBA values.

This code can be executed when the mousemove map event is fired, as shown in the below code snippet from the answer to this SO post:

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

As also noted in the linked SO post, the map's preserveDrawingBuffer parameter must be set to true, as shown below. The parameter is set to false by default as a performance optimization.

var map = new mapboxgl.Map({
    container: 'map', // container id
    style: 'mapbox://styles/mapbox/streets-v11', // stylesheet location
    center: [-74.50, 40], // starting position [lng, lat]
    zoom: 9, // starting zoom
    preserveDrawingBuffer: true // preserve the buffer where fragment colors are written, comes with a performance cost
});

This JSFiddle demonstrates the above functionality, along with an HTML element displaying the retrieved RGBA values. You can run the example by replacing /* ADD YOUR MAPBOX ACCESS TOKEN HERE */ with your own Mapbox access token.

Upvotes: 1

Related Questions