user3625375 user3625375 - 1 year ago 81
Javascript Question

How to get a pixel's color value from an Openlayers 3 layer?

Is there a way to read pixel color values of an Openlayers 3 layer?
Something like this:

layerid.getPixelColor(x, y);

I'm aware of the getImageData() method used with the canvas, but as far as I can see, this only allows you to get the proper color values of the top layer with 100% alpha.

I want to get the colors from lower or even hidden layers. (WMS tiles from same domain.)

Answer Source

You can set a postcompose handler directly on a layer and read the pixel value from there. I made a small example based on the layer spy example:

imagery.on('postcompose', function(event) {
  var ctx = event.context;
  var pixelRatio = event.frameState.pixelRatio;
  if (mousePosition) {
    var x = mousePosition[0] * pixelRatio;
    var y = mousePosition[1] * pixelRatio;
    var data = ctx.getImageData(x, y, 1, 1).data;
    var color = 'rgb(' + data[0] + ',' + data[1] + ','+ data[2] + ')';
    $('#box').css('background-color', color);

You might also be interested in ol.Map.html#hasFeatureAtPixel.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download