簡體   English   中英

如何在openlayers3中更改圖像顏色?

[英]How to change image color in openlayers3?

我是openlayers3的新手。 我正在將點顯示為圖像,但我想動態更改圖像的顏色.openlayers3中是否可能,或者openlayers3中是否有畫布之類的其他功能?

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' 
    })) 
}); 

圖標顏色為起點,在它們使用帶有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

暫無
暫無

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

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