2

I'm building a little React application with the purpose of

  • Able to move shapes on a canvas
  • Save the state of the canvas
  • Use REST API to upload/load from state

So far my application allows me to move shapes on the canvas and then save the state of the canvas by using React's useRef and then saving the value of stageRef:

const stageRef = useRef();
...
<Stage width={500} height={500} ref={stageRef}>
   ...(Layers and shapes)
</Stage>

This method works (in terms of saving the state) but I am unsure if using useRef is an unsafe way to handle saving state and if there is a better way.

I am using Konva for my canvas library which contains Stages, Layers, Shapes - which ultimately get saved.

Thanks for your time.

callsuper
  • 89
  • 11

1 Answers1

4

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?

  1. The structure of stage.toJSON() may change over time. It is an internal format for Konva to save and load the state.

  2. 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.

  3. Your data and savings should be framework-agnostic. Just in case you will decide to use something else for drawing instead of Konva.

lavrton
  • 18,973
  • 4
  • 30
  • 63