问题描述:

I try to add on my map an image mask on the foreground, some kind of shadow frame.

The problem is that I've not been able to find a good solution to do so by trying:

  • precompose/postcompose overload (drawing the image with the canvas's ctx)
  • adding a layer
  • adding an overlay
  • adding a div over the map (events propagation issues and jQuery exceptions)

Has anyone faced this problem?

网友答案:

A solution is to bind on postcompose event. Here is the JS code making it working:



    var osm = new ol.layer.Tile({
      source: new ol.source.OSM()
    });

    var map = new ol.Map({
      layers: [osm],
      target: 'map',
      controls: ol.control.defaults({
        attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
          collapsible: false
        })
      }),
      view: new ol.View({
        center: [0, 0],
        zoom: 5
      })
    });

    var image = new Image();
    var loaded = false;
    image.src = 'http://safari.am/images/frame_shadow.png';
    image.onload = function() {
        loaded = true;
    };

    osm.on('postcompose', function(event) {
        var ctx = event.context;
        if(loaded)
            ctx.drawImage(image, 0, 0);
        ctx.restore();
    });


You can find the full solution in the following JSFiddle

相关阅读:
Top