如何在openlayers3中更改图像颜色?

时间:2017-06-07 14:12:36

标签: javascript html css html5-canvas openlayers-3

我是openlayers3的新手。我将点显示为图像,但我想动态地更改图像的颜色。是否可以在openlayers3中或在openlayers3中使用任何其他设施,如canvas?

var iconStyle = new ol.style.Style({ 
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
         anchor: [0.5, 46], 
         anchorXUnits: 'fraction', 
         anchorYUnits: 'pixels', 
         src: 'data/icon.png' 
    })) 
}); 

1 个答案:

答案 0 :(得分:0)

Icon Colors为起点,他们使用带ol.Color选项的透明PNG来获得多个颜色点我试图改变这样的颜色而没有成功......

var london = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.12755, 51.507222]))
});


london.setStyle(new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    color: '#ff0000',
    crossOrigin: 'anonymous',
    src: 'https://openlayers.org/en/v4.1.1/examples/data/dot.png'
  }))
}));


var vectorSource = new ol.source.Vector({
  features: [london]
});

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

var rasterLayer = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
    crossOrigin: ''
  })
});

var map = new ol.Map({
  layers: [rasterLayer, vectorLayer],
  target: document.getElementById('map'),
  view: new ol.View({
    center: ol.proj.fromLonLat([2.896372, 44.60240]),
    zoom: 3
  })
});

map.on('singleclick', function (event) { // Use 'pointermove' to capture mouse movement over the feature 
  map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {
    /* Get the current image instance and its color */
    var image = feature.getStyle().getImage();
    console.log(image.getColor());
    
    /* Color gets stored in image.i, but there's no setter */
    console.log(image.i);
    
    /* Trying to force the color change: */
    image.i = [0, 255, 0, 1];
    
    /* Dispatch the changed() event on layer, to force styles reload */
    layer.changed();
    
    console.log(image.getColor()); // Logs new color, but it doesn't work...
    
  });
});
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.1.1/build/ol.js"></script>
<div id="map" class="map"></div>

了解如何检索图标的颜色:

var image = feature.getStyle().getImage(),
    color = image.getColor(); // returns [R, G, B, alpha]

但是没有setColor()方法,因此无法在运行时更改颜色...

编辑:再次审核您的问题和代码,我注意到您从未为图标设置颜色,所以也许您真的不想实际更改响应事件的颜色,但只是设置一种颜色。如果这就是你想要的,那就很简单:

var iconStyle = new ol.style.Style({ 
     image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
         anchor: [0.5, 46], 
         anchorXUnits: 'fraction', 
         anchorYUnits: 'pixels', 
         src: 'data/icon.png',
         color: '#ff0000' // allows HEX as String or RGB(a) as Array
     })) 
});

请参阅:http://openlayers.org/en/latest/apidoc/ol.style.Icon.html

相关问题