如何序列化和反序列化自定义Konva Shape?
Konva允许您使用sceneFunc创建自定义形状,但是当您将其存储到JSON并加载回去时,您如何知道它是什么自定义形状?
答案 0 :(得分:2)
要定义自定义形状,您需要定义sceneFunc
Demo:
function mySceneFunc(context, shape) {
context.beginPath();
context.rect(0, 0, shape.getAttr('width'), shape.getAttr('height'));
context.fillStrokeShape(shape);
}
var rect = new Konva.Shape({
fill: '#00D2FF',
width: 100,
height: 50,
name: 'my-custom-rect',
sceneFunc: mySceneFunc
});
不建议将函数序列化为JSON。因此,默认情况下,node.toJSON()
将不具有sceneFunc
属性。
要恢复自定义形状,只需在反序列化后的阶段中找到这种形状,然后手动应用sceneFunc
。您可以将自己的名称设置为此类形状,以便轻松找到它们。
var json =
'{"attrs":{"width":758,"height":300},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"fill":"#00D2FF","width": 100, "height": 100, "name": "my-custom-rect" },"className":"Shape"}]}]}';
// create node using json string
var stage = Konva.Node.create(json, 'container');
function mySceneFunc(context, shape) {
context.beginPath();
context.rect(0, 0, shape.getAttr('width'), shape.getAttr('height'));
context.fillStrokeShape(shape);
}
stage.find('.my-custom-rect').sceneFunc(mySceneFunc);
stage.draw()