使用openlayers绘制带方向箭头导航线(五)
前言
之前博客中与大家分享了使用数据去绘制导航线的思路及实现,有朋友私信问能否让绘制的导航线的箭头在线上流动起来,接下来就提将思路与大家分享;
实现思路
- 还是延续之前的思路绘制线与箭头,计算箭头的位置及方向,这边就不再赘述,假如有需要的可以翻看前几篇博文;
- 监听 ol.layer.vector 的 postrender 事件,即图层渲染结束事件;
- 当渲染结束事件触发的时候,重新计算下一帧动画中的箭头位置及方向,然后渲染图层;
关键代码分解
通过注释将关键代码每一步分解;
代码逻辑
init(){
//初始化图层
this.olSource_line = new VectorSource();
this.olLayer_line = new VectorLayer({
source: this.olSource_line,
style: (feature)=>{
let coords = feature.getGeometry().getCoordinates();
return [
new Style({
stroke: new Stroke({
color: this.style.line_stroke,
width: this.style.line_width,
})
}),
...this.getPointsStyle(coords)
]
},
});
//添加图层至地图
this.olMap.addLayer(this.olLayer_line);
//监控图层渲染完成事件
this.olLayer_line.on("postrender",this.animation.bind(this))
}
//动画
animation(){
//初始帧将第一个点的位置设置为0,即线的开始点的位置;
//每次触发动画的时候,将第一个点移动一个像素;
this.first_++;
//当超过一个间隔的时候,返回其实位置;
this.first_ = this.first_ % this.style.interval;
//然后重新设置样式,触发渲染;
this.olLayer_line.setStyle(this.olLayer_line.getStyle())
}
调用
调用方式与之前博文中一致;
效果展示
后记
码字不易,希望您能喜欢,如有不同的想法或者建议欢迎在评论区讨论!