如何导出画布到JSON?
使用Konva将舞台保存为JSON字符串,可以使用toJSON()
方法将Konva节点树序列化为可保存的文本
在网络存储或离线数据库中。我们也可以序列化其他节点,
包括层、组和形状。
toJSON()方法不能保存过滤器、图像和事件监听器。所以它适用于非常小的应用程序。对于更复杂的情况,请阅读最佳实践
将整个舞台转换为json 和转换为对象
转换都是按照 “”树“”结构的
let stageJson = stage.toJSON()
// {"attrs":{"width":1200,"height":800},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"name":"rect","x":37,"y":34,"width":41,"height":35,"fill":"red","strokeWidth":0,"opacity":0.5,"draggable":true},"className":"Rect"}]}]}
let stageObj = JSON.parse(stageJson)
/**
attrs:
height: 800
width: 1200
[[Prototype]]: Object
children: Array(1)
0:
attrs: {}
children: Array(1)
0:
attrs: {name: 'rect', x: 37, y: 34, width: 41, height: 35, …}
className: "Rect"
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
className: "Layer"
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
className: "Stage"
*/