html - 使 <svg> 的宽度增长以匹配它的 <text> 的长度

标签 html css svg

我有一个 React 组件,它显示 <svg> .有一个 <text>随时间变化的属性。我想要 <svg>增加宽度以显示完整的 text .如何使跟随组件的大小随文本的长度动态变化?

const S = {
    Container: styled.div`
        background: red;
        width: '10px';
        height: '10px';
    `
};

export class RectNode extends Component<IRectNodeProps> {
    render() {
        return (
            <S.Container>
                <svg width="auto" height="auto">
                    <rect
                        x="0"
                        y="0"
                        width="100%"
                        height="100%"
                        stroke="red"
                        stroke-width="3px"
                        fill="white"
                    />
                    // more shapes here
                    <text
                        x="50%"
                        y="50%"
                        dominant-baseline="middle"
                        text-anchor="middle"
                    >
                        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa
                    </text>
                </svg>
            </S.Container>
        );
    }
}

JS fiddle :

<svg width="auto" height="auto">
  <rect
        x="0"
        y="0"
        width="100%"
        height="100%"
        stroke="red"
        stroke-width="3px"
        fill="white"
        />
  // more shapes here
  <text
        x="50%"
        y="50%"
        dominant-baseline="middle"
        text-anchor="middle"
        >
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa
  </text>
</svg>

最佳答案

渲染后获取文本BBox,通过改变状态设置SVG宽度属性。示例 here .

class SvgComponent extends React.Component {
    state = {width: 0};

    componentDidMount() {
        this.updateTextSize();
    }

    componentDidUpdate() {
        this.updateTextSize();
    }

    updateTextSize() {
        const box = this.text.getBBox();
        if(this.state.width !== box.width) {
            this.setState({width: box.width});
        }
    }

    render() {
        return (
        <svg width={this.state.width} height="40">
            <text ref={handle => this.text = handle} x="50%" y="25" textAnchor="middle">
                {this.props.text}
            </text>
        </svg>
        );
    }
}

关于html - 使 <svg> 的宽度增长以匹配它的 <text> 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335108/

相关文章:

javascript - 数组长度在清空后不会增加,并且无法在 HTMLCollection 上添加鼠标事件

javascript - 如何增加谷歌地图自动完成搜索下拉文本的字体大小?

css - 如何使用变换矩阵修改 svg 路径数据

html - 调整 SVG <path> 图像大小以适应 16x16px

javascript - 如何设置跨源 header 以允许数据 URL?

javascript - 在正确的输入上使用 js 重新启用提交按钮

jquery - CSS:背景重复增量

javascript - 拉斐尔命中检测

javascript - 将 div 缩放到背景图像高度

javascript - 事件菜单部分高度问题