Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
vojtech.osvald Avatar asked Jan 20 '26 03:01

vojtech.osvald


1 Answers

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
});
like image 171
Viglino Jean-Marc Avatar answered Jan 22 '26 15:01

Viglino Jean-Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!