2

I would like to add a mask to clip layers (Tile) below in a way that only the part bounded by a ol.Feature (polygon or multipolygon) is visible and the rest is hidden (left white). The polygon is stored in a DB so I need a way to do that programatically.

Does anybody have some clues or examples to achieve this?

  • ol.Overlay?
  • ol.layer.Vector filled with white outside of the features

Ideally: - add / remove vector features and interactions should update the mask - swichting layer below the mask is possible

I'm not looking for a working code but more inspirations and ideas to start doing that in a "ol3" way.

6

This can easily be done adding an Image layer with an ImageVector source on top of the tile layer. The ImageVector layer's precompose and postcompose hooks are used to change the global canvas composite operation:

var clipLayer = new ol.layer.Image({
  source: new ol.source.ImageVector({
    source: new ol.source.Vector({
      // contains your clip polygon
    }),
    style: new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'black'
      })
    })
  })
});
clipLayer.on('precompose', function(e) {
  e.context.globalCompositeOperation = 'destination-in';
});
clipLayer.on('postcompose', function(e) {
  e.context.globalCompositeOperation = 'source-over';
});

Working example: http://jsfiddle.net/2gy96vbv/

  • Waw, thanks. I would never imagine that we can have a working example with less than 20 lines of codes! – Simon Daron Mar 22 '16 at 9:33
  • 2
    @ahocevar: Is there an easy way to apply the clipping to only specific layers? e.g: clip an image layer but leave the background layers as is? – Constantinius Feb 10 '17 at 9:12
  • @Constantinius You may look at gis.stackexchange.com/questions/281164/… for a solution – ThomasG77 Apr 28 '18 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.