Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify() Unable to save Object ID Fabric JS

I am setting an id attribute for a Group Object

group.id = "N";
canvas.add(group);
canvas.renderAll();

Now, When I am serializing the canvas using

JSON.stringify(canvas);

And then reloading the Canvas using the Json Saved

canvas.loadFromJSON(canvas_json , canvas.renderAll.bind(canvas) , function(o , obj)
{
    if(obj.type == 'group')
    {
       console.log('OBJ ID -'+obj.id);
    }
});

I get OBJ ID -undefined

I checked a few solutions some involve subclassing, but since I am pretty deep in the application it won't be the best solution for me.

I tried something like

fabric.Object.prototype.toObject = (function (toObject) {
return function () {
    return fabric.util.object.extend(toObject.call(this), {
        id: this.id
    });
};

But it was in vain. Do I have to loop through each object in the canvas and manually add the id attribute to the json? I am sure there must be a better solution than that.

Any help in this regards would be very helpful.

like image 832
Genocide_Hoax Avatar asked Jan 06 '23 22:01

Genocide_Hoax


1 Answers

Check out the function toObject(propertiesToInclude) on the canvas object (fabric.js doc). You should use this method to "export" the canvas before using JSON.stringify to serializing. The function allows you to provide a list of additional properties that should be included in the serialization.

When deserializing you just use the reviver function to set the needed property from o to obj (obj.id = o.id).

Putting it all together:

var canvas, group; // your canvas and group objects
group.id = 'N';
canvas.add(group)
canvas.renderAll();

var canvasJson = JSON.stringify(canvas.toObject(['id']));

canvas.loadFromJSON(canvasJson, canvas.renderAll.bind(canvas), function(jsonObject, fabricObject) {
    // jsonObject is the object as represented in the canvasJson
    // fabricObject is the object that fabric created from this jsonObject
    if (fabricObject.type === 'group') {
        fabricObject.id = jsonObject.id
    }
});
like image 129
forrert Avatar answered Jan 08 '23 11:01

forrert