Search code examples
konva

Konva serialization and deserialization of a custom shape


How do you serialize and deserialize a custom Konva Shape?

Konva allows you to create a custom shape with the sceneFunc, but when you store it to JSON and load it back, how do you know what custom shape it is?


Solution

  • To define a custom shape you need to define 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
    });
    

    It is not recommended to serialize functions into JSON. So by default node.toJSON() will not have sceneFunc property.

    To restore your custom shape you just need to find such shapes in your stage after deserialization and then apply sceneFunc manually. You can set your own name to such shapes to easily find them.

    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()
    

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