fabric js- extending toObject method with additional property added are missing when saving and loading back to canvas

血红的双手。 提交于 2019-12-13 03:49:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!