Search code examples
javascriptdictionarycanvasopenlayersopenlayers-6

How to get canvas from postcompose event of map in openlayers 6


We are using openlayers and in version 5.3 we were using this construction:

map.once('postcompose', async(event) => {
  let canvas = event.context.canvas;
  // doing something with canvas
}

But in openLayers 6.0 the argument context is undefined for event (which of course broke our application).

I read here that:

Layers are no longer composed to a single Canvas element. Instead, they are added to the map viewport as individual elements.

So how do I get the canvas of a single layer?

I also read here that:

Canvas context. Not available when the event is dispatched by the map. Only available when a Canvas renderer is used, null otherwise.

Is it somehow possible to set canvas renderer to all the layers so that CanvasRenderingContext2D is not undefined for the 'postcompose' event?


Solution

  • With ol6 use postrender event on layers and new getVectorContext function provides access to the immediate vector rendering API.
    See https://github.com/openlayers/openlayers/releases/tag/v6.0.0

    To get render context on a single layer:

    import {getVectorContext} from 'ol/render';
    
    // construct your map and layers as usual
    
    layer.on('postrender', function(event) {
      const vectorContext = getVectorContext(event);
      // use any of the drawing methods on the vector context
    });