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

react-konva How to set stage width and height to be equal to its container?

我想将舞台的宽度和高度设置为等于其div容器,在我的情况下,它是className为" drawing-area"的div

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const Canvas = props => {
    return <Row>
        <Col xs={12} className="canvas-container">
           
                <Stage width={450} height={200}>
                    <Layer>
                        <BoxSurface/>
                        <UserText text={props.text}/>
                        <DesignImage image={props.image}/>
                        <Handler image={props.image}/>
                    </Layer>
                </Stage>
           
        </Col>
    </Row>;
};

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

非常感谢你。


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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>
     
    );
  }
}

演示:https://codesandbox.io/s/8k2m333m92
也看看这个评论-https://github.com/konvajs/konva/issues/321#issuecomment-377459992