如何在 openlayers 功能中将文本移动到左上角而不是左下角?

问题描述 投票:0回答:1
addLabelBox(labelBoxData) {
        const newFeature = new Feature(this.feature.getGeometry());

        const textStyle = new Style({
            fill: new Fill({
                color: 'rgba(162, 72, 87, 1)'
            }),
            stroke: new Stroke({
                color: 'rgba(0, 0, 0, 1)',
                width: 2
            }),
            text: new Text({
                text: labelBoxData.text,
                font: '12px sans-serif',
                fill: new Fill({ color: '#fff' }),
                placement: 'line',
                textBaseline: 'bottom',
                textAlign: 'left'
            })
        });

        // Set the style for the new feature
        newFeature.setStyle(textStyle);

        this.labelBoxesLayer.getSource().addFeature(newFeature);
    }

我正在使用此函数与文本一起创建矩形特征,但我面临的问题是文本呈现在左下角,而不是如图所示的左上角。 Example

我已经尝试过“placement”和“textBaseline”的所有可能组合,但无法做到。此外,如果文本的长度比框长,则文本会消失,而不是文本分成多行。我正在使用 textarea 元素来添加文本。任何建议都会有帮助。

javascript reactjs openlayers openlayers-6 openlayers-5
1个回答
0
投票

您不认为您可以选择使用多边形线放置的哪个面。相反,您可以将文本分离为单独的样式并为其设置点几何

const textStyle = [
  new Style({
    fill: new Fill({
      color: 'rgba(162, 72, 87, 1)
    }),
    stroke: new Stroke({
      color: 'rgba(0, 0, 0, 1)',
      width: 2
    }),
  }),
  new Style({
    geometry: function (feature) {
      return new Point(getTopLeft(feature.getGeometry().getExtent()));
    },
    text: new Text({
      text: labelBoxData.text,
      font: '12px sans-serif',
      fill: new Fill({color: '#fff'}),
      placement: 'point',
      textBaseline: 'top',
      textAlign: 'left'
    }),
  })
];
© www.soinside.com 2019 - 2024. All rights reserved.