Improve example with a background layer, intersect and comments

This commit is contained in:
Simon Daron
2020-04-26 13:27:04 +02:00
parent 71f056c75c
commit 8cfe994ff0

View File

@@ -1,39 +1,56 @@
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {Fill, Style} from '../src/ol/style.js'; import {Fill, Style} from '../src/ol/style.js';
import {OSM, Stamen, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import {getVectorContext} from '../src/ol/render.js'; import {getVectorContext} from '../src/ol/render.js';
import {intersects} from '../src/ol/extent.js';
//A distinct className is required to use another canvas for the background
const background = new TileLayer({
className: 'stamen',
source: new Stamen({
layer: 'toner',
}),
});
const base = new TileLayer({ const base = new TileLayer({
source: new OSM(), source: new OSM(),
}); });
const clipLayer = new VectorLayer({ const clipLayer = new VectorLayer({
style: new Style({ style: null,
fill: new Fill({
color: 'black',
}),
}),
source: new VectorSource({ source: new VectorSource({
url: './data/geojson/switzerland.geojson', url: './data/geojson/switzerland.geojson',
format: new GeoJSON(), format: new GeoJSON(),
}), }),
}); });
clipLayer.on('prerender', function (e) { const style = new Style({
e.context.globalCompositeOperation = 'destination-in'; fill: new Fill({
color: 'black',
}),
}); });
clipLayer.on('postrender', function (e) { base.on('postrender', function (e) {
const vectorContext = getVectorContext(e);
e.context.globalCompositeOperation = 'destination-in';
//Checking interect is required so the base layer is totally hidden when not clipped
if (intersects(e.frameState.extent, clipLayer.getSource().getExtent())) {
clipLayer.getSource().forEachFeature(function (feature) {
vectorContext.drawFeature(feature, style);
});
} else {
e.context.fillStyle = 'transparent';
e.context.fillRect(0, 0, 1, 1);
}
e.context.globalCompositeOperation = 'source-over'; e.context.globalCompositeOperation = 'source-over';
}); });
const map = new Map({ const map = new Map({
layers: [base, clipLayer], layers: [background, base, clipLayer],
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat([8.23, 46.86]), center: fromLonLat([8.23, 46.86]),