我想将舞台的宽度和高度设置为等于它的 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/