在标记区域内,我写了一些文字。当我缩小时,文本在Area之外消失并消失。有什么办法可以防止这种情况?
我试图根据缩放大小更改文本大小,以使其始终在区域内匹配并且永不消失,但仅捕获一次缩放,以后不进行任何更改。
我的代码下面。
var styleText = function(text) {
var zoom = map.getView().getZoom();
var resolution = map.getView().getResolution();
var font = zoom * 3
return {
text: new ol.style.Text({
font: font+'px Courier New',
fill: new ol.style.Fill({
color: '#ffd300'
}),
stroke: new ol.style.Stroke({
color: '#000',
width: 3
}),
textAlign: "center",
textBaseline: "middle",
text: text,
})
}
}
var newVector = new ol.layer.Vector({
name: areaIncra.farmId,
source: kmlVector,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
text: styleText('Text to show').text
})
});
答案 0 :(得分:2)
要重新计算的样式必须是一个函数
style: function(feature, resolution) { return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
text: styleText('Text to show').text
}); }
您可能还希望在overflow: true
https://openlayers.org/en/v4.6.5/apidoc/ol.style.Text.html上设置ol.style.Text
var styleText = function(text) {
var zoom = map.getView().getZoom();
var resolution = map.getView().getResolution();
var font = (zoom + 1) * 3;
return {
text: new ol.style.Text({
font: font+'px Courier New',
fill: new ol.style.Fill({
color: '#ffd300'
}),
stroke: new ol.style.Stroke({
color: '#000',
width: 3
}),
textAlign: "center",
textBaseline: "middle",
text: text,
overflow: true
})
}
}
var newVector = new ol.layer.Vector({
source: new ol.source.Vector(),
style: function(feature, resolution) {
return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
text: styleText('Text to show').text
});
}
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
newVector
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
map.addInteraction(new ol.interaction.Draw({
source: newVector.getSource(),
type: 'Polygon',
}));
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>