跳到主要内容

如何使用 Vue 和 Konva 保存及加载 Canvas?

如何使用 Vue 序列化和反序列化 Konva 舞台?

原生 Konva 可以使用 node.toJSON() 序列化节点树及其可序列化属性。它可以使用 Konva.Node.create(json) 恢复这些内容。图像、事件处理函数和自定义绘制函数必须单独恢复。 查看示例

使用 vue-konva 时,请在 Vue 组件中定义应用 state。state 通过模板映射到节点。请保存并加载应用 state,而不是 Konva 内部数据和节点。

操作说明:单击 Canvas 以创建圆形。重新加载页面后,圆形应继续存在。

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