Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load from JSON in Fabric.js loading default properties

Tags:

fabricjs

I have canvas which contains objects with centeredRotation:true and other object with selectable:false When I convert this canvas into JSON and reload it. The objects are with their default properties. i.e no centered rotation and object is selectable. May I know why this is happening? Clearly the properties like centeredRotation, selectable are not included in JSON.

{"type":"rect","originX":"left","originY":"top","left":92,"top":53,"width":150,"height":150,"fill":"#778899","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":0.4,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","rx":0,"ry":0,"x":0,"y":0}],"background":""}

How to set these while loading the objects?

like image 764
John Avatar asked Dec 16 '22 05:12

John


2 Answers

You need to include them during toJSON:

canvas.toJSON([ 'centeredRotation', 'selectable' ]);

See documentation for toJSON which describes this "propertiesToInclude" argument and has some examples.

like image 70
kangax Avatar answered Jan 28 '23 18:01

kangax


You can also specify this on the main object before you create anymore new objects. This guarantees for me that the next time I load an object from json, the selectable will be saved in the "toObject"/"toJSON" function.

// Add 'selectable' to every object via the main class "Object"
fabric.Object.prototype.toObject = (function (toObject) {
    return function () {
        return fabric.util.object.extend(toObject.call(this), {
            selectable: this.selectable
        });
    };
})(fabric.Object.prototype.toObject);

I don't understand why this isn't there by default, but I guess it is because it is more of a state vs a property?

like image 23
teewuane Avatar answered Jan 28 '23 18:01

teewuane