Search code examples
serializationmetadatafabricjs

Fabric.js: How to serialize/deserialize some global data? How to extend the canvas object?


How can I add additional properties to the canvas object so that they get serialized/deserialized? E.g. I'd like to store a name for the data that I get with canvas.toJSON() and that I store on the server-side.

Does it make sense to extend the canvas this way? Or would you recommend to create a "meta object" that contains my additianal data and one property for the canvas json?


Solution

  • You can pass an array with additional properties into Canvas.toJSON() method like this:

    const canvas = new fabric.Canvas('c')
    canvas.myProp = 'MyCanvas'
    
    const serializedCanvas = canvas.toJSON(['myProp'])
    console.log(serializedCanvas.myProp) // 'MyCanvas'
    

    Note that this array is also passed into every object's _toObject() method during the serialization, so it makes sense to keep the custom property list to a minimum.