自定义形状的 Konva 序列化和反序列化

Konva serialization and deserialization of a custom shape

如何序列化和反序列化自定义 Konva Shape?

Konva 允许您使用 sceneFunc 创建自定义形状,但是当您将其存储到 JSON 并加载回来时,您如何知道它是什么自定义形状?

要定义自定义形状,您需要定义 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()

演示:https://jsbin.com/sadehigina/1/edit?html,js,output