【问题标题】:Konva serialization and deserialization of a custom shape自定义形状的Konva序列化和反序列化
【发布时间】:2020-05-25 22:58:48
【问题描述】:

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

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

【问题讨论】:

    标签: konva


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多