I want to add a dashed stroke with two alternating colors to a feature in OpenLayers. Basically, I want to create a two color outline around polygon so that it shows up no matter what color the background is. I want the end result to look like this;
How can I define that kind of style in OpenLayers?
The style property of a Vector layer accepts an array of values in addition to a single value, so you can create two dashed strokes using lineDash
and give them different lineDashOffset
values;
var lightStroke = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [255, 255, 255, 0.6],
width: 2,
lineDash: [4,8],
lineDashOffset: 6
})
});
var darkStroke = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 0, 0, 0.6],
width: 2,
lineDash: [4,8]
})
});
Then apply them to the same layer like this;
var myVectorLayer = new ol.layer.Vector({
source: myPolygon,
style: [lightStroke, darkStroke]
});
Style in Vector Layer can fill by array of styles or function.
public styles = {
'Point': new Style({
image: this.image
}),
'LineString': new Style({
stroke: new Stroke({
color: 'green',
lineDash: [4],
width: 2
})
}),
'Polygon': new Style({
stroke: new Stroke({
color: 'blue',
lineDash: [4],
width: 3
}),
fill: new Fill({
color: 'rgba(255, 0, 255, 0.1)'
})
}),
'Circle': new Style({
stroke: new Stroke({
color: 'red',
width: 2
}),
fill: new Fill({
color: 'rgba(255,0,0,0.2)'
})
})
};
var vector = new VectorLayer({
source: new VectorSource({}),
style: (feature, resolution) => {
switch (feature.getGeometry().getType()){
case 'Polygon':
return this.styles['Polygon'];
case 'LineString':
return this.styles['LineString'];
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With