You can use ref
to get access to any Konva
node. You can use Konva
methods to save JSON somewhere. It will work just fine:
const stageRef = useRef();
const handleSave = () => {
const json = stageRef.current.toJSON();
}
<Stage width={500} height={500} ref={stageRef}>
...(Layers and shapes)
</Stage>
BUT I don't recommend to use that.
Your questions is related to undo/redo react-konva demo and JSON saving best practices from Konva.
As you are using react
and react-konva
it is better to avoid using Konva internals.
You must have your own state of the app. It can be a simple react state or some external lib like mobx
or redux
or anything else.
Just save that state to the backend:
const [shapes, setShapes] = React.useState([]);
const handleSave = () => {
const json = JSON.stringify(shapes);
}
<Stage width={500} height={500} ref={stageRef}>
...(Layers and shapes drawn from the state)
</Stage>
Why it is better to use the state of the app, instead of Konva's JSON?
The structure of stage.toJSON()
may change over time. It is an internal format for Konva to save and load the state.
stage.toJSON()
may have a piece of noise information that makes your JSON bigger. For example, for each shape, it will have fill
property. But it is possible that in your app it doesn't make sense to save that property, since all your shapes are red all the time.
Your data and savings should be framework-agnostic. Just in case you will decide to use something else for drawing instead of Konva
.