Skip to main content

How to save and load canvas with Vue and Konva?

How to serialize and deserialize Konva stage with Vue?

Pure Konva can serialize a node tree and its serializable attributes with node.toJSON(). It can restore them with Konva.Node.create(json). Restore images, event handlers, and custom drawing functions separately. See demo.

With vue-konva, define the application state in your Vue components. The state maps to nodes through templates. Save and load the application state instead of Konva internals and nodes.

Instructions: Click on the canvas to create circles. Reload the page - the circles should persist.

<template>
<div>
Click on canvas to create a circle.
<a href=".">Reload the page</a>. Circles should stay here.
<v-stage
ref="stage"
:config="stageSize"
@click="handleClick"
>
<v-layer ref="layer">
<v-circle
v-for="item in list"
:key="item.id"
:config="item"
/>
</v-layer>
</v-stage>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};

const list = ref([{ x: 100, y: 100, radius: 50, fill: 'blue' }]);

const handleClick = (evt) => {
const stage = evt.target.getStage();
const pos = stage.getPointerPosition();
list.value.push({
radius: 50,
fill: 'red',
...pos
});

save();
};

const load = () => {
const data = localStorage.getItem('storage');
if (data) list.value = JSON.parse(data);
};

const save = () => {
localStorage.setItem('storage', JSON.stringify(list.value));
};

onMounted(() => {
load();
});
</script>