Get RGB color of pixel on hover
Get the RGB color of the pixel being hovered over in a Mapbox GL JS map.
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.css">
<div id='map'></div>
<pre id='info'>
<div id='color'></div>
<div id='text'>rgba(-, -, -, -)</div>
</pre>
CSS
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
#info {
display: inline-block;
position: relative;
width: 220px;
margin: 10px auto;
padding: 10px;
border-radius: 3px;
font-size: 12px;
color: #222;
background: #fff;
display: flex;
justify-content: center;
}
#color {
width: 16px;
height: 16px;
border-radius: 25%;
border: 2px solid black;
}
#text {
line-height: 16px;
padding: 2px 0 2px 6px;
}
JavaScript
mapboxgl.accessToken = /* ADD YOUR MAPBOX ACCESS TOKEN HERE */;
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
});
function RGBToHex(r,g,b) {
r = r.toString(16);
g = g.toString(16);
b = b.toString(16);
if (r.length == 1)
r = "0" + r;
if (g.length == 1)
g = "0" + g;
if (b.length == 1)
b = "0" + b;
return "#" + r + g + b;
}
map.on("mousemove", e => {
const canvas = map.getCanvas();
const gl = canvas.getContext('webgl') || canvas.getContext('webgl2');
const colorStyle = document.getElementById("color").style;
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}`);
colorStyle.backgroundColor = color;
document.getElementById('text').innerHTML = color;
}
})