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

标签 reactjs html5-canvas konvajs

我想将舞台的宽度和高度设置为等于它的 div 容器,在我的例子中,它是类名为“drawing-area”的 div

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>;
};

因为当我像上面那样固定宽度和高度时,当屏幕尺寸改变时,布局会被破坏。

非常感谢。

最佳答案

这个想法很简单。从 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

关于reactjs - react-konva 如何设置舞台宽度和高度等于其容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49962244/

相关文章:

javascript - 像 React 中的 Bootstrap 模态行为

javascript - 为什么不 moveTo(0, 0); lineTo(X, X);画一条45°线?

javascript - 用圆锯切割板的动画

konvajs - 通过在konva中的对象周围画一个框来选择

javascript - 为什么自动绑定(bind)的 Prop 会在运行时通过 propTypes 产生警告消息?

reactjs - ComponentDidMount() 中 Axios 请求的 Jest/Enzyme 单元测试

css - 在右侧显示嵌套组件,在左侧显示父组件

javascript - 旋转 Canvas 图像,同时保持纵横比

stage - 在html中绘制Konvajs容器Stage的边框边缘

javascript - KonvaJS:event.preventDefault 不是函数