效果:
其中重要代码:
var mask = new ol.filter.Mask({
feature: feature,
fill: new ol.style.Fill({
color: [0, 0, 0, 0.5]
})
});
xyzLayer.addFilter(mask);
完整代码:
<!DOCTYPE html>
<html>
<head>
<title>Mask遮罩</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Openlayers -->
<link rel="stylesheet" href="https://openlayers.org/en/latest/css/ol.css" />
<script type="text/javascript" src="https://openlayers.org/en/latest/build/ol.js"></script>
<!-- ol-ext -->
<script type="text/javascript" src="./dist/ol-ext.js"></script>
<style>
html,
body,
.map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var xyzLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
})
});
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 14.5,
center: [12127495.117988808, 4058905.64276462]
}),
layers: [xyzLayer]
});
// 添加边界数据
var maskSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: './data/xiaozhai_3857.geojson'
})
var maskLayer = new ol.layer.Vector({
source: maskSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#5fcac7',
width: 3
}),
})
})
map.addLayer(maskLayer)
maskSource.on('featuresloadend', (obj) => {
addMask(obj.features[0])
})
// 添加遮罩
function addMask(feature){
var mask = new ol.filter.Mask({
feature: feature,
fill: new ol.style.Fill({
color: [0, 0, 0, 0.5]
})
});
xyzLayer.addFilter(mask);
}
</script>
</body>
</html>