官网文档ol/style/text部分:OpenLayers v8.1.0 API - Module: ol/style/Text
代码如下:
var coordinate = [[10711293.51783087, 1900921.581665377],
[10711332.930673579, 1900920.9845010934],
[10711337.707987847, 1900825.4382157368],
[10711293.51783087, 1900826.0353800203]];
var geometry = new ol.geom.LineString([]);
geometry.setCoordinates(coordinate);
view.setCenter([10711293.51783087, 1900921.581665377]);
view.setZoom(18);
var LineStringFeature = new ol.Feature(geometry);
LineStringFeature.set('name', '线段') //设置属性
var source = new ol.source.Vector();
source.addFeature(LineStringFeature);
var vectorLayer = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#f00',
width: 6
}),
//关键代码
text: new ol.style.Text({
text: '线段', //文本内容
// maxAngle: 'Math.PI',
offsetX: '40', //水平文本偏移量(以像素为单位),正数将向右移动文本
offsetY: '80', //垂直文本偏移量(以像素为单位),正数将向下移动文本。
// overflow: true,
// placement: 'Polygon',
// repeat: 4,
scale: 2, //文本规模
rotateWithView: true, //是否随视图一起旋转文本
textAlign: 'center', //文本对齐方式
textBaseline: 'middle', //文本基线
fill: new ol.style.Fill({
color: 'green',
}), //填充样式
stroke: new ol.style.Stroke({
color: 'red',
width: 1
}), //描边样式
backgroundFill: new ol.style.Fill({
color: 'yellow',
}), //文本背景的填充样式
backgroundStroke: new ol.style.Stroke({
color: 'black',
width: 2,
lineDash: [2, 3]
}), //文本背景边框样式
font: ' 48px serif', //字体样式
padding: [25, 5, 5, 5] //在文本周围填充像素,用于整理和背景:背景内边距
}),
})
});
map.addLayer(vectorLayer);
效果如下:
如有错误欢迎指正!!!