Search code examples
jsonpaperjs

Adding additional object properties in PaperJS to export them


I try to export to JSON and import them after, in a paperJS project. The problem is the following. The object has a additional properties like 'idLine' for example, but, when I export the item, it loose all additional properties. By the way, the properties are added with:

    new paper.Path(strPath, {idLine : 1})

I find something similar in fabricJS, but nothing more than this. https://github.com/kangax/fabric.js/wiki/Adding-additional-object-properties-to-serialized-JSON


Solution

  • To export data along with paper Items, you just need to set your data in the Item.data attribute.

    For example:

     var cirle = new Path.Circle({ center: new Point(150, 50),  radius: 25 });
     cirle.fillColor = 'darkGreen'
     cirle.data = 'someData'
    
     var rectangle = new Path.Rectangle(new Point(50, 100), new Point(250, 150));
     rectangle.fillColor = 'darkBlue'
     rectangle.data = {size: 50, message: 'some other data'}
    
     var json = project.exportJSON();
    

    Here is a sketch that exports to JSON with the data of the paths.