Skip to content

Instantly share code, notes, and snippets.

@elemoine
Created October 8, 2014 12:08
Show Gist options
  • Save elemoine/b95420de2db3707f2e89 to your computer and use it in GitHub Desktop.
Save elemoine/b95420de2db3707f2e89 to your computer and use it in GitHub Desktop.
OpenLayers 3 – clip layer with geometry

OpenLayers 3 – clip layer with geometry

This gist shows how to clip a layer with a geometry, i.e. a shape with geographical coordinates.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<link rel="stylesheet" href="http://openlayers.org/en/master/css/ol.css" type="text/css">
<style type="text/css">
body {
width: 960px;
height: 500px;
position: relative;
}
#map {
width: 100%;
height: 100%;
}
</style>
<title>Clip layer with geometry</title>
</head>
<body>
<div id="map"></div>
<script src="http://openlayers.org/en/master/build/ol.js" type="text/javascript"></script>
<script type="text/javascript">
// The layer to clip.
var osm = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
target: 'map',
layers: [osm],
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
// The clipping geometry.
var circleGeometry = new ol.geom.Circle(
[1000000, 1000000], 5000000);
// A style for the geometry.
var fillStyle = new ol.style.Fill({color: [0, 0, 0, 0]});
osm.on('precompose', function(event) {
var ctx = event.context;
var vecCtx = event.vectorContext;
ctx.save();
// Using a style is a hack to workaround a limitation in
// OpenLayers 3, where a geometry will not be draw if no
// style has been provided.
vecCtx.setFillStrokeStyle(fillStyle, null);
vecCtx.drawCircleGeometry(circleGeometry);
ctx.clip();
});
osm.on('postcompose', function(event) {
var ctx = event.context;
ctx.restore();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment