OpenLayers 3: per-layer translation for tiled imag

2019-09-08 04:22发布

问题:

Sometimes it's useful to apply translation (that is, pixel offset) to a layer (and not other layers).

For example, two line-based layers can be visually compared by translating (that is, offsetting) a layer.

For vector layers, it can be done by translating vector features. But for the tiled image layers, (for example, road traffic information tiles generated by GeoServer) how can it be done?

回答1:

This is also a nice example for precompose and postcompose render event handlers.

precompose is triggered before a layer is rendered, and postcompose afterwards. Inside the event handlers you have direct access to the canvas context, so you can use CanvasRenderingContext2D.translate() to offset the rendering for a layer.

roads2.on('precompose', function(event) {
  var ctx = event.context;
  ctx.save();
  ctx.translate(10, 10);
});

roads2.on('postcompose', function(event) {
  var ctx = event.context;
  ctx.restore();
});

http://jsfiddle.net/m1abjrkm/3/

Note: This example does not take into account rotated maps!

Update: As @zeodtr points out in his comment, there is a problem at the tile borders with this approach. The following screenshot created by him illustrates the problem: