Vector Clipping Layer example
Example of a clipping layer based on a vector source
<!DOCTYPE html>
<html lang="en">
<head>
<title>Vector Clipping Layer</title>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL"></script>
<style>
.map {
width: 100%;
height:400px;
}
#map {
background: transparent;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import OSM from 'ol/source/OSM';
import {Fill, Style} from 'ol/style';
import {getVectorContext} from 'ol/render';
import {fromLonLat} from 'ol/proj';
var base = new TileLayer({
source: new OSM()
});
var clipLayer = new VectorLayer({
style: null,
source: new VectorSource({
url:
'./data/geojson/switzerland.geojson',
format: new GeoJSON()
})
});
var style = new Style({
fill: new Fill({
color: 'black'
})
});
base.on('postrender', function(e) {
e.context.globalCompositeOperation = 'destination-in';
var vectorContext = getVectorContext(e);
clipLayer.getSource().forEachFeature(function(feature) {
vectorContext.drawFeature(feature, style);
});
e.context.globalCompositeOperation = 'source-over';
});
var map = new Map({
layers: [base, clipLayer],
target: 'map',
view: new View({
center: fromLonLat([8.23, 46.86]),
zoom: 7
})
});
{
"name": "layer-clipping-vector",
"dependencies": {
"ol": "6.3.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}