Search code examples
openlayersopenlayers-6

How to auto-resize a shape's font in Openlayers 6?


I used Openlayers to draw characters and shapes.

I want to change the characters size dynamically according to the size of the shapes.

function setStyle(feature: RenderFeature | Feature<any>, resolution: number): void | Style | Style[] {
  const props: IProps = feature.getProperties()
  const options: IStyleOptions = this.styleOptions(props)
  // const area: number = feature.getGeometry().getArea()
  const fontSize: number = Math.floor(1 / resolution)
  const style: Style = new Style({
    fill: new Fill({
      color: options.fillColor
    }),
    stroke: new Stroke({
      color: options.strokeColor,
      width: 1
    }),
    text: new Text({
      font: `bold ${fontSize}px/1 Malgun Gothic`,
      text: options.text,
      overflow: true
    })
  })
  return style
}

This is the resulting image of the code above


Solution

  • There is no easy solution for irregular shapes, but if your shapes are rectangles you would need to consider their width and height, along with the maximum number of lines and characters in a line

      const width: number = getWidth(feature.getGeometry().getExtent())
      const height: number = getHeight(feature.getGeometry().getExtent())
      const fontSize: number = Math.min(width / (maxchars * resolution), height / (maxlines * resolution))