Pure SVG way to fit text to a box

后端 未结 4 637
小鲜肉
小鲜肉 2020-12-07 13:21

Box size known. Text string length unknown. Fit text to box without ruining its aspect ratio.

\"enter

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 13:40

    I've developed @Roberto answer, but instead of transforming (scaling) the textNode, we simply:

    • give it font-size of 1em to begin with
    • calculate the scale based on getBBox
    • set the font-size to that scale

    (You can also use 1px etc.)

    Here's the React HOC that does this:

    import React from 'react';
    import TextBox from './TextBox';
    
    const AutoFitTextBox = TextBoxComponent =>
      class extends React.Component {
        constructor(props) {
          super(props);
          this.svgTextNode = React.createRef();
          this.state = { scale: 1 };
        }
    
        componentDidMount() {
          const { width, height } = this.props;
          const textBBox = this.getTextBBox();
          const widthScale = width / textBBox.width;
          const heightScale = height / textBBox.height;
          const scale = Math.min(widthScale, heightScale);
    
          this.setState({ scale });
        }
    
        getTextBBox() {
          const svgTextNode = this.svgTextNode.current;
          return svgTextNode.getBBox();
        }
    
        render() {
          const { scale } = this.state;
          return (
            
          );
        }
      };
    
    export default AutoFitTextBox(TextBox);
    

提交回复
热议问题