概述
上文中提过Openlayers
如何用图片填充面,那么我们如何用图片或图标去填充线条呢?在面的填充,我们是平铺的,没有方向,在水平垂直方向重复就完事,但是在线的填充就没有这么简单粗暴了,因为线往往是首尾两端有方向的,比如当线条表示线路图时,pattern
就有些力不从心了。
效果
解决方案
StyleFunction
Openlayers
中设置样式除了Style
的stroke
和fill
往,还提供了另一种方式,即StyleFunction
。
StyleFunction
不是属性名,确切来说是一种类型,比如通过feature.setStyle(styleFunction)
设置样式时,如果参数是一个函数,那么它就是StyleFunction
Openlayers
官网中是这样定义的:
A function that takes a Feature and a {number} representing the view’s resolution. The function should return a Style or an array of them. This way e.g. a vector layer can be styled. If the function returns undefined, the feature will not be rendered.
翻译过来就是StyleFunction
接收两个参数Feature
和Number
类型的值,分别表示feature
本身和视图范围内地图的分辨率。这个函数应该返回一个Style
类型或者Style
类型的数组,通过这种方式,可以设置矢量图层(要素)的样式,如果函数没有返回值,则要素feature
不会被渲染。
经过测试在StyleFunction
中拿到的第二个参数即分辨率number
是会动态变化的,当我们拖动地图时,这个值会跟着变化。
由此,我们可以在在其中做文章。
示例代码
示例如下:
export const getStyleFunction = ({
steps,
color,
width,
imgsrc,
scale,
wrapperRotation,
})