效果图
实现原理简单描述
Openlayers 图层的渲染大多数都是通过 canvas实现,在图层渲染前后事件中通过canvas控制渲染区域即可实现。
代码
点击查看代码
componentDidMount() {
this.map = this.mapRef.getMap();
this.init();
}
init = () => {
let geoJson = new GeoJSON();
this.creatPolygonClip(this.map, this.mapRef.basicLayer, geoJson.readFeatures(JSON.stringify(mostchinaJson))[0].getGeometry());
}
creatPolygonClip = (map, layer, polygonGeometry) => {
layer.on('prerender', (evt) => {
const canvas = evt.context;
canvas.save();
canvas.beginPath();
const coords = polygonGeometry.getCoordinates()[0];
this.createClip_(map, coords, canvas);
canvas.clip();
});
layer.on('postrender', function (evt) {
const canvas = evt.context;
canvas.restore();
});
}
createClip_ = (map, coords, canvas) => {
for (let i = 0, cout = coords.length; i < cout; i++) {
const screenCoord = map.getPixelFromCoordinate(coords[i]);
const x = screenCoord[0],
y = screenCoord[1];
if (i === 0) {
canvas.moveTo(x, y);
} else {
canvas.lineTo(x, y);
}
}
canvas.closePath();
canvas.strokeStyle = "rgba(0,0,0,0)";
canvas.stroke();
}
小问题
个人测试不能使用 MultiPolygon,所以效果图上其实漏了台湾、海南和南海的地方。
只能用笨办法多渲染几个图层实现效果,如果有更好的方法希望能分享一下。