react-konva如何将舞台宽度和高度设置为等于其容器?

时间:2018-04-22 03:33:21

标签: reactjs html5-canvas konvajs

我想将舞台的宽度和高度设置为等于它的div容器,在我的例子中,它是带有className" div-area"

const Canvas = props => {
    return <Row>
        <Col xs={12} className="canvas-container">
            <div className="drawing-area">
                <Stage width={450} height={200}>
                    <Layer>
                        <BoxSurface/>
                        <UserText text={props.text}/>
                        <DesignImage image={props.image}/>
                        <Handler image={props.image}/>
                    </Layer>
                </Stage>
            </div>
        </Col>
    </Row>;
};

因为当我设置宽度和高度如上所述固定时,当屏幕尺寸改变时,布局将被破坏。

非常感谢。

1 个答案:

答案 0 :(得分:2)

这个想法很简单。从DOM获取容器大小,然后使用该大小更新阶段。在需要时重新计算DOM元素(和阶段)的大小。

class App extends Component {
  state = {
    stageWidth: 1000
  };
  componentDidMount() {
    this.checkSize();
    // here we should add listener for "container" resize
    // take a look here https://developers.google.com/web/updates/2016/10/resizeobserver
    // for simplicity I will just listen window resize
    window.addEventListener("resize", this.checkSize);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.checkSize);
  }

  checkSize = () => {
    const width = this.container.offsetWidth;
    this.setState({
      stageWidth: width
    });
  };
  render() {
    const radius = this.state.stageWidth / 2;
    return (
      <div
        style={{
          width: "50%",
          border: "1px solid grey"
        }}
        ref={node => {
          this.container = node;
        }}
      >
        <Stage width={this.state.stageWidth} height={window.innerHeight}>
          <Layer>
            <Circle x={radius} y={radius} radius={radius} fill="red" />
          </Layer>
        </Stage>
      </div>
    );
  }
}

演示:https://codesandbox.io/s/8k2m333m92 另请查看此评论 - https://github.com/konvajs/konva/issues/321#issuecomment-377459992