openlayers使用Canvas实现行政区划遮罩地图

有时候我们做GIS开发时需要只显示某个区域的地图,需要把其他地方遮罩住,比如下图这样:

openlayers使用Canvas实现行政区划遮罩地图_第1张图片

好了,上代码:

//添加遮罩
    function clipmap(data) {
        $.getJSON(data, function(data) {
            var fts = new ol.format.GeoJSON().readFeatures(data);
            var ft = fts[0];
            var converGeom =ft.getGeometry()
            converGeom.applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
            //var convertFt =new  ol.Feature(converGeom);
            //converLayer.getSource().addFeature(convertFt);
            var center,pixelScale,offsetX,offsetY,rotation;
            map.on('precompose',function(evt) {
                var canvas=evt.context;
                canvas.save();
               
                var coords=converGeom.getCoordinates();
                var frameState = evt.frameState;
                var pixelRatio = frameState.pixelRatio;
                var viewState = frameState.viewState;
                center = viewState.center;
                var resolution = viewState.resolution;
                rotation = viewState.rotation;
                var size = frameState.size;
                var size1=map.getSize();
                offsetX = Math.round(pixelRatio * size[0] / 2);
                offsetY = Math.round(pixelRatio * size[1] / 2);
                pixelScale = pixelRatio / resolution;

                canvas.beginPath();
                if(converGeom.getType() == 'MultiPolygon'){
                    for(var i=0;i

示例网址:

http://www.mapmonster.cn:7000/exapmles/openlayers/base_add_geojson_clip_canvas.html

 

你可能感兴趣的:(Openlayers)