In my current project I want to build something like Image Editor with react and react-konva.
First of all, I render a konva stage with some props and default draggable stars.
In the next step we can set background image for our stage using Image
from react-konva.
<Stage width={konvaWidth} height={height - 150} className={classes.canvas} onClick={test}>
<Layer>
{image && bg && <Image
x={0}
y={0}
image={bg}
scaleX={0.35}
scaleY={0.35}
ref={node => {
imageRef = node;
}}
/>}
<Text text="Try to drag a star" />
{[...Array(10)].map((_, i) => (
<Star
key={i}
x={Math.random() * window.innerWidth}
y={Math.random() * window.innerHeight}
numPoints={5}
innerRadius={20}
outerRadius={40}
fill="#89b717"
opacity={0.8}
draggable
rotation={Math.random() * 180}
shadowColor="black"
shadowBlur={10}
shadowOpacity={0.6}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
/>
))}
</Layer>
</Stage>
The next, and finally step.
Can we save konva stage to json format?
The Konva
API has toJSON()
method. You can convert any node (like Stage) into json.
https://konvajs.org/docs/data_and_serialization/Serialize_a_Stage.html
For more complex cases (like if you have images, filters): https://konvajs.org/docs/data_and_serialization/Best_Practices.html
BUT if you are using react I don't recommend to use Konva
methods to serialize the canvas rendering.
In your react you must have a state of your app. In can be any state library (mobx, redux) or just setState
or useState
of React or anything else. Usually, that state is easily serializable to JSON.