效果图
和上一篇博客一样使用的是 setInterval 但是处理方式不一样
const vectorlayer = new VectorLayer({
source: new VectorSource({
features: new GeoJSON().readFeatures(
{
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {},
geometry: {
coordinates: [
[117.283042, 31.86119],
[120.63149446427894, 31.07331888747879],
[120.68147825813776, 31.07510268306622],
[120.77519787161987, 31.08818282802015],
[120.812685717014, 31.127412459737243],
[120.84114871073785, 31.114932062363565]
],
type: 'LineString'
}
}
]
},
{
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
}
)
}),
style: [
// 实线
new Style({
stroke: new Stroke({
color: 'rgba(30,144,255, 1)',
width: 3,
lineDash: [0]
}),
text: new Text({
text: '流动效果',
fill: new Fill({ color: '#000' }),
font: '18px Arial',
offsetY: 20,
placement: 'line'
})
}),
// 虚线
new Style({
stroke: new Stroke({
color: [255, 250, 250, 1],
width: 3,
lineDash: [20, 27],
// 一组线段和间距交互的数组,可以控制虚线的长度
lineDashOffset: 0
})
})
]
})
window.olMap.addLayer(vectorlayer)
// 定时赋值
setInterval(() => {
let lineDashOffset = vectorlayer.getStyle()[1].getStroke().getLineDashOffset()
vectorlayer.setStyle([
vectorlayer.getStyle()[0],
// 虚线
new Style({
stroke: new Stroke({
color: [204, 204, 255, 1],
width: 3,
lineDash: [10, 25],
lineDashOffset: lineDashOffset == 100 ? 0 : lineDashOffset + 2
})
})
])
}, 50)