Search code examples
javascripthtmlhtml5-canvaskineticjs

Best way to export stage in kineticjs


I'm looking for best way to export kinetic stage to json. Is there any solution to export objects with events, and custom attributes?


Solution

  • As you've discovered, object.toJSON will not serialize your event handlers.

    So you must:

    • Use toJSON to serialize most of the object, and

    • Put your KineticJS event handlers in a separate .js file, and

    • Rewire them up after you deserialize the object.

    Here's an example that almost automatically rewires the events:

    Step#1: Create a separate kEvents.js file with the event handlers defined in an object:

    // the eventHandlers object contains all the event handling functions
    // for the serialized object(s).
    
    var eventHandlers={
        myClickHandler1:function(e){alert("Fired clickHandler1");},
        myOtherClickHandler:function(e){alert("Fired the other clickHandler");},
    }
    

    Step#2: Add some attributes to your Kinetic nodes that indicate which handler(s) to rewire:

    // this circle will be rewired with the click handler named "myClickHandler1"
    
    var circle1 = new Kinetic.Circle({
        x:100,
        y:100,
        radius: 30,
        fill: 'red',
        stroke: 'black',
        strokeWidth: 4,
        draggable: true,
    
        // Below: 
        // "clickEvent" attribute indicates this node needs their click event rewired
        // "myClickHandler1" is the name of the handler function that will be rewired
    
        clickEvent:"myClickHandler1"
    });
    

    Step#3: Import the kEvents.js file

    <script src="http://yourSite.com/kEvents.js"></script>
    

    Step#4: Run a function that attaches the handlers in eventHandlers to the objects:

    function rewireHandlers(node){
    
        var handler;
    
        // rewire click handler
    
        handler=node.getAttr("clickEvent");
        if(handler && eventHandlers[handler]){
            node.on("click",eventHandlers[handler])
        }
    
        // rewire other event handlers the same way
    
    }