项目中有时候需要突出显示(或者只显示)需要的区域,遮罩其他不需要的区域,这就是经常遇到的地图权限问题,如下图所示:
只用openlayers是无法解决的,需要配合H5中的canvas来实现。
var bianjieSource=new ol.source.Vector({
features: (new ol.format.GeoJSON({featureProjection: 'EPSG:4326'})).readFeatures(data),
})
vec_c.on('precompose', clip);
cva_c.on('precompose', clip);
function clip(evt) {
var canvas=evt.context;
canvas.save();
var coords = bianjieSource.getFeatures()[0].getGeometry().getCoordinates();
canvas.beginPath();
createClip(coords[0], canvas);
canvas.clip();
}
function createClip(coords, canvas) {
for (var i = 0, cout = coords.length; i < cout; i++) {
//获取屏幕坐标
var screenCoord = map.getPixelFromCoordinate(coords[i]);
var x = screenCoord[0],
y = screenCoord[1];
if (i === 0) {
canvas.moveTo(x, y);
} else {
canvas.lineTo(x, y);
}
}
canvas.closePath();
//设置边框
canvas.strokeStyle = "#dedede";
canvas.lineWidth = 2;
canvas.stroke();
}
vec_c.on('postcompose', function(event) {
var ctx = event.context;
ctx.restore();
});
cva_c.on('postcompose', function(event) {
var ctx = event.context;
ctx.restore();
});
其中的data是边界数据。