Search code examples
jsonkineticjs

In kineticjs, is it possible to save complex shapes to json and restore it?


I can't seem to to get it to work. I know you can do that with built in shape functions such as circle, polygon but for complex shapes, it can still serialize but if you look at the json string, you don't see x,y coordinate. jsfiddle.net/Q7G99/1/. The serialize and de-serialize don't give any errors but nothing appear on the canvas.


Solution

  • The "primitive" shapes (Kinetic.Rect, Kinetic.Circle, etc) use properties to define their shapes.

    The Kinetic.Shape uses context drawing commands to define the shape.

    Properties can be serialized -- drawing commands cannot.

    That's why Kinetic.Shape does not completely serialize.

    As a workaround, save your sceneFunc function in a .js file that's loaded with your page.

    Eg. In myShapeSceneFuncs.js:

    // this is the sceneFunc code from var shape1=new Kinetic.Shape
    
    function Shape1SceneFunc(context) {
        context.beginPath();
        context.moveTo(200, 50);
        context.lineTo(420, 80);
        context.quadraticCurveTo(300, 100, 260, 170);
        context.closePath();
        // KineticJS specific context method
        context.fillStrokeShape(this);
    } 
    
    // rewire sceneFunc back into shape1
    
    shape1.sceneFunc(Shape1SceneFunc);