簡體   English   中英

使用顏色選擇器更改圖層樣式顏色

[英]change layer style color using color picker

我正在嘗試在地圖中創建一個工具,以選擇要應用於特定圖層的顏色。 我試圖像下面的代碼一樣隨機更改顏色:

function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;

    }

var ab =new ol.layer.Vector({
  source: vectorSource,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'rgba(0, 0, 255, 0.0)',
      width: 0.3
    }),
     fill : new ol.style.Fill({
   color: getRandomColor()
  })
  })
});
var map = new ol.Map({
  layers: [
  new ol.layer.Tile({ source: new ol.source.OSM() }),
  ab
  ],
  target: document.getElementById('mapid'),
  view: new ol.View({
    center: [-1095791.453557, 3422374.879112],
    maxZoom: 19,
    zoom: 5
  })
});

我發現了類似的東西: https : //jsfiddle.net/7g7Lh2L2/2/

但是我不知道如何用圖層專有'#background'替換'#background''background-color'

謝謝;

您應該創建一個樣式函數,以使用fill屬性實現所需的內容。 樣式函數將為地圖圖層中的每個對象調用,您可以檢查特征的屬性以確定其fill或調用getRandomColor()函數:

var styleFunction = function() {
  return function(feature,resolution) {
    var style;
    var objProperty = feature.get('<Layer Property Name>'); //Retrieve feature property value
    style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        fill: createFillStyle(feature),  //Would call function for each map layer feature to determine fill color
        stroke: createStrokeStyle(feature,resolution) //Example calls function to create stroke for an individual layer feature
      }),
      text: createTextStyle(feature, resolution) //Example calls function to create text style for individual layer feature
    });
    return [style];
  };
};

var ab =new ol.layer.Vector({
  source: vectorSource,
  style: styleFunction()
});

var createFillStyle = function(feature) {
  var fillColor = getRandomColor();
  return new ol.style.Fill({color: fillColor});
}

上面的示例將為地圖層上的每個要素調用getRandomColor() (每個要素在地圖層上具有不同的顏色)。 如果地圖圖層上的所有var ab =new ol.layer.Vector只有一種顏色,請在var ab =new ol.layer.Vector之前調用getRandomColor() var ab =new ol.layer.Vector地圖上的所有地圖var ab =new ol.layer.Vector設置一種隨機顏色。

搜索openlayers style function以獲取更多示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM