Reputation:
I want to set the width and height of my Stage to 100%. Kind of like this, so that it fills the parent div:
<Stage
width="100%"
height="100%"
></Stage>
Is this possible? Thanks!
Upvotes: 4
Views: 12456
Reputation: 356
Since we cannot set the width and height of to "100%", we have to instead find the width and height of its parent container in pixels and then set those values for the the width and height
import React, { useEffect, useRef, useState } from "react"
import { Stage, Layer, Rect } from "react-konva"
export const View = () => {
const divRef = useRef(null)
const [dimensions, setDimensions] = useState({
width: 0,
height: 0
})
// We cant set the h & w on Stage to 100% it only takes px values so we have to
// find the parent container's w and h and then manually set those !
useEffect(() => {
if (divRef.current?.offsetHeight && divRef.current?.offsetWidth) {
setDimensions({
width: divRef.current.offsetWidth,
height: divRef.current.offsetHeight
})
}
}, [])
return (
<div ref={divRef}>
<Stage width={dimensions.width} height={dimensions.height}>
<Layer>
<Rect fill="red" x={0} y={0} width={150} height={150}></Rect>
</Layer>
</Stage>
</div>
)
}
Upvotes: 10
Reputation: 20288
No. You have to set the Konva.Stage
size with pixels value.
If you want to use 100%
values, you need to set such values to the parent <div>
container of the stage with CSS. Then calculate the size of that <div>
in pixels and use it for Stage.
Take a look into Responsive Canvas Stage Demo.
var container = document.querySelector('#stage-parent');
stage.width(container.offsetWidth);
stage.height(container.offsetHeight);
Upvotes: 4