Skip to main content

HTML5 Canvas 阶段序列化教程

要使用 Konva 序列化一个阶段,我们可以使用 toJSON() 方法。 toJSON() 方法将返回一个包含所有节点属性的 JSON 字符串。 请注意,事件处理程序和图像是不可序列化的。

import Konva from 'konva';

// 创建具有相对定位的封装
const stage = new Konva.Stage({
container: 'container',
width: 400,
height: 400
});

const layer = new Konva.Layer();
stage.add(layer);

const circle = new Konva.Circle({
x: 100,
y: 100,
radius: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 3
});

layer.add(circle);

// 在舞台上方添加按钮
const button = document.createElement('button');
button.textContent = '序列化阶段';
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
document.body.appendChild(button);

button.addEventListener('click', () => {
const json = stage.toJSON();
console.log(json);
alert('阶段已序列化!请检查控制台以获取 JSON 字符串。');
});