用React计算SVG边界框?

时间:2017-06-25 16:11:28

标签: javascript reactjs svg

我正在编写一个可视化应用程序,其中React生成SVG。我需要的一个部分是一个标签 - 即文本,由一个封闭的盒子包围,带有可变文本,可能是旋转和样式化的。

所以我有NodeLabel的组件,目前有固定的尺寸:

render() {
        return <g>
            <rect className="label" x={this.props.x} y={this.props.y-10} width={20} height={40}></rect>
            <text className="labelText" x={this.props.x} y={this.props.y}>{this.props.children}</text>
        </g>
    }

我在DOM中找到了一些关于这样做的信息:Rectangle border around SVG text

但我还没有完全看到如何将其转换为React组件 - 在render()方法中,没有要查看的DOM元素。我是否可以只使用document.createElement()并期望SVG元素的维度正常运行(并尊重CSS)?另外,有没有办法避免基本上创建代码的两个副本,一个在JSX中,另一个在此之前用于计算维度? (比如,例如,为这个临时的屏幕外拷贝评估JSX到DOM元素的片段)

更新:2018年1月,我又回到了这里:-)实际的应用程序是一个开源的网络图表工具,目前正在使用GD和PHP,但我希望转向JS,React和SVG。 / p>

此处的带宽标签是我尝试重现的标签,尽管节点标签在当前的非SVG版本中使用相同的功能。

The bandwidth labels here are what I'm trying to reproduce, although the node labels use the same function in the current non-SVG version.

这是我的新例子:

&#13;
&#13;
// MyLabel should be centred at x,y, rotated by angle, 
// and have a bounding box around it, 2px from the text.
class MyLabel extends React.Component {
  render() {
    const label = <text x={this.props.x} y={this.props.y} textAnchor="middle" alignmentBaseline="central">{this.props.children}</text>;
        
    // label isn't a DOM element, so you can't call label.getBoundingClientRect() or getBBox()

    // (Magic happens here to find bbox of label..)        
    // make up a static one for now
    let bb = {x: this.props.x-20, y: this.props.y-6, width: 40, height: 12};
    
    // add margin
    const margin = 2;
    bb.width += margin * 2;
    bb.height += margin * 2;
    bb.x -= margin;
    bb.y -= margin;
    
    // rect uses bbox to decide its size and position
    const outline = <rect x={bb.x} y={bb.y} width={bb.width} height={bb.height} className="labeloutline"></rect>;
    
    const rot = `rotate(${this.props.angle} ${this.props.x} ${this.props.y})`;
    // build the final label (plus an x,y spot for now)
    return <g transform={rot}>{outline}{label}<circle cx={this.props.x} cy={this.props.y} r="2" fill="red" /></g>;
  }
}

class Application extends React.Component {
  render() {
    return <svg width={300} height={300}>
      <MyLabel x={100} y={100} angle={0}>Dalmation</MyLabel>
      <MyLabel x={200} y={100} angle={45}>Cocker Spaniel</MyLabel>
      <MyLabel x={100} y={200} angle={145}>Pug</MyLabel>
      <MyLabel x={200} y={200} angle={315}>Pomeranian</MyLabel>
    </svg>;
  }
}

/*
 * Render the above component into the div#app
 */
ReactDOM.render(<Application />, document.getElementById('app'));
&#13;
body { background: gray; }
svg {background: lightgray;}
.labeloutline { fill: white; stroke: black;}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

您可以预先计算/测量字体几何,并根据输入字符串得到合理的文本尺寸估计(这是最简单的解决方案,但如果字体更改,很明显会中断),或者执行两阶段渲染:

也就是说,你通过ref获取dom元素,获取mount上的框,最后通过更新状态重新渲染,如:

class MyLabel extends React.Component {
  constructor(props){
    super(props);
    this.state = {text_extents:null};
  }
  componentDidMount() {
   const box = this.text.getBBox();

   this.setState({text_extents:[box.width,box.height]});
  }
 render() {
   const margin = 2;
   const extents = this.state.text_extents;
   const label = <text ref={(t) => { this.text = t; }} textAnchor="middle" dy={extents?(extents[1]/4):0} >{this.props.children}</text>;
   const outline = extents ?
         <rect x={-extents[0]/2-margin} y={-extents[1]/2-margin} width={extents[0]+2*margin} height={extents[1]+2*margin} className="labeloutline"></rect>
         : null;

   return <g transform={`translate(${this.props.x},${this.props.y}) rotate(${this.props.angle})`}>{outline}{label}</g>;
 }
}

请注意,根据最新的反应文档,这不会导致任何用户可见的闪烁:

  

componentDidMount():在此方法中调用setState()将触发额外的渲染,但它将在浏览器更新屏幕之前发生。这保证了即使在这种情况下将调用render()两次,用户也不会看到中间状态。请谨慎使用此模式,因为它通常会导致性能问题。但是,在需要测量DOM节点然后再渲染依赖于其大小或位置的东西时,它可能需要像模态和工具提示这样的情况。

最后,请注意,如果标签字符串发生更改(通过道具或其他),您需要相应地更新范围(通过componentDidUpdate())。

答案 1 :(得分:0)

// MyLabel should be centred at x,y, rotated by angle, 
// and have a bounding box around it, 2px from the text.
class MyLabel extends React.Component {
state={
x:this.props.x,
y:this.props.y,
width: 40,
height: 12,
angle: this.props.angle,
}
componentDidMount() {
 var reactDomElem = this.label.getBBox()
 //console.log(reactDomElem)
 this.setState({
 width:reactDomElem.width,
 height:reactDomElem.height,
 x:reactDomElem.x,
 y:reactDomElem.y,
 angle: this.state.angle,
 })
}
  render() {
    const label = <text ref={(ref)=>this.label = ref} x={this.state.x} y={this.state.y} textAnchor="middle" alignmentBaseline="baseline">{this.props.children}</text>;
        
    // label isn't a DOM element, so you can't call label.getBoundingClientRect() or getBBox()

    // (Magic happens here to find bbox of label..)        
    // make up a static one for now
    let bb = {x: this.state.x, y: this.state.y, width:this.state.width, height: this.state.height};
    
    // add margin
    const margin = 2;
    bb.width += margin * 2;
    bb.height += margin * 2;
    bb.x -= this.state.width/2;
    bb.y -= this.state.height/2 + margin*2;
    
    // rect uses bbox to decide its size and position
    const outline = <rect x={bb.x} y={bb.y} width={bb.width} height={bb.height} className="labeloutline"></rect>;
    
    const rot = `rotate(${this.state.angle} ${this.state.x} ${this.state.y})`;
    // build the final label (plus an x,y spot for now)
    return <g  transform={rot}>{outline}{label}<circle cx={this.state.x} cy={this.state.y} r="2" fill="red" /></g>;
  }
}

class Application extends React.Component {
  render() {
    return <svg width={300} height={300}>
      <MyLabel x={100} y={100} angle={0}>Dalmation</MyLabel>
      <MyLabel x={200} y={100} angle={45}>Cocker Spaniel</MyLabel>
      <MyLabel x={100} y={200} angle={145}>Pug</MyLabel>
      <MyLabel x={200} y={200} angle={315}>Pomeranian</MyLabel>
    </svg>;
  }
}

/*
 * Render the above component into the div#app
 */
ReactDOM.render(<Application />, document.getElementById('app'));
body { background: gray; }
svg {background: lightgray;}
.labeloutline { fill: white; stroke: black;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

相关问题