Reputation: 3509
I want to set the stage width and height to be equal to it's div container, in my case, it's the div with className "drawing-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>;
};
Because when I set width and height fixed like above, when the screen size is changed, the layout will be broken.
Thank you very much.
Upvotes: 3
Views: 10910
Reputation: 20373
The idea is simple. Get container size from DOM, then update stage with that size. Recalculate size of DOM element (and stage) when required.
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>
);
}
}
Demo: https://codesandbox.io/s/8k2m333m92 Also take a look at this comment - https://github.com/konvajs/konva/issues/321#issuecomment-377459992
Upvotes: 6