简体   繁体   中英

Customize style of a vector layer ol3

I use a geojson file to build the layer added to a map. What I want is to customize style of the layer's polygons in order to have hatched polygons such as we can do that with mapserver symbols. Is it possible to do this with ol3? I tried to create an image and use it but it only works for point geometry. Thank you for your help. Regards.

OpenLayers 3目前尚不支持多边形的填充图案,另请参见https://github.com/openlayers/ol3/issues/2208

It is possible by now. The ol.style.Style object accepts a CanvasRenderingContext2D instance, where you can apply an image pattern to your polygons.

Example Code Snippet

var geojsonObject = 'someGeoJSON' 
var source = new ol.source.Vector({
 features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

var layer = new ol.layer.Vector({
source: source
});

var cnv = document.createElement('canvas');
var ctx = cnv.getContext('2d');
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = function() {
  var pattern = ctx.createPattern(img, 'repeat');
  layer.setStyle(new ol.style.Style({
    fill: new ol.style.Fill({
      color: pattern
   })
 }));
};

A full example can be seen here: jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM