In openlayers 3, how to fill the polygon with a picture from a url?

丶灬走出姿态 提交于 2020-01-25 04:40:09

问题


I would like to add a picture in the polygon, however, I do not find such function in openlayers 3. Is there any way to achieve this?

Thanks in advance!


回答1:


Since Pull Request #4632 you can use a CanvasRenderingContext2D.fillStyle as ol.style.Fill#color property and create a pattern.

Something like this:

var cnv = document.createElement('canvas');
var ctx = cnv.getContext('2d');
var img = new Image();
img.src = 'https://i.imgsafe.org/73d1273.png';

img.onload = function(){
  var pattern = ctx.createPattern(img, 'repeat');

  // featurePoly is ol.Feature(new ol.geom.Polygon(...))
  featurePoly.setStyle(new ol.style.Style({
    fill: new ol.style.Fill({
      color: pattern
    })
  }));
};

Live demo.




回答2:


I am not sure what would be the visual output of your requirement but I may give you the direction to solve your problem.

OL3 can use predifined styles or an array of styles or even a function that returns a style for each feature supplied. So you should propably use the style function to achieve your goal. Lets say that you want to place one image within every vector polygon. Consider the following code snip

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'http://openlayers.org/en/v3.14.0/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature, resolution) {
   var styles = [
    new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#ffcc33',
        width: 2
      }),
      fill: new ol.style.Fill({
      color: 'rgba(255,0,0,0.5)'
      })
    })
  ];
  var mygeomType = feature.getGeometry().getType();
  //handle the case of polygons/multipolygons
  var retGeom = null;
  if (mygeomType === 'MultiPolygon'){
 //get the interior points for every polygon of the multipolygon
  retGeom = feature.getGeometry().getInteriorPoints();
  }
  if (mygeomType === 'Polygon'){
 //just get the interiot point of the simple polygon
  retGeom = feature.getGeometry().getInteriorPoint();
  }
  styles.push(new ol.style.Style({
      geometry: retGeom,
      image: new ol.style.Icon({
        src: 'http://openlayers.org/en/master/examples/data/icon.png',
        anchor: [0.75, 0.5],
        rotateWithView: true
      })
    }));
 return styles;  
}});

check this fiddle to see it in action.



来源:https://stackoverflow.com/questions/36835929/in-openlayers-3-how-to-fill-the-polygon-with-a-picture-from-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!