问题
I have created a fabric group with a rectangle and text. finally Iam adding a custom property 'name' to group class using the below code.
Iam serializing the canvas data into JSON using JSON.stringify(canvas) and sending the Json string to java and finally saving the Json string into file , custom property are also saved with the file.
var rect1= createRect(104,166,250,15);
var text1 = new fabric.Text('hello', { left: rect1.get('left'), top: rect1.get('top'),fontSize: 13 });
var group1=new fabric.Group([rect1,text1]);
group1.toObject = (function(toObject) {
return function() {
return fabric.util.object.extend(toObject.call(this), {
name: this.name
});
};
})(group1.toObject);
canvas.add(group1);
group1.name = 'New group';
Iam reading the same file using java and trying load the Json into canvas like this canvas.loadFromJSON(jsonVal) my custom properties are missing. Json group with rectangle and text gets loaded with default properties only.
how to load Json string back into canvas without losing the custom properties can someone please help me with this.
回答1:
According to the Fabricjs documentation https://github.com/kangax/fabric.js/wiki/Adding-additional-object-properties-to-serialized-JSON
Properties should be returned from toObject method of fabric.Object or from toObject method of a more specific "class".
So you either add your properties to the toObject method of fabric.Object or you add it to the the toObject method of fabric.Group. You cannot add it to an object as group1, as group1 is not a valid reference in the JSON string at load .
So, this should work ( I tried it ):
fabric.Group.prototype.toObject = (function(toObject) {
return function() {
return fabric.util.object.extend(toObject.call(this), {
name: this.name
});
};
})(fabric.Group.prototype.toObject);
来源:https://stackoverflow.com/questions/46441206/fabric-js-extending-toobject-method-with-additional-property-added-are-missing