Fabric js extending toObject with custom properties, loses default ones

假如想象 提交于 2019-12-07 08:55:11

问题


Befor posting this I've been looking up in here as in many other places, but I can get to have this working fully.

All I need is to be able to save some custom properties in all the shapes. The properties are : uuid, and rt_attributes.

Therefore, as by manual I added this code :

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

which does work fine, up to a certain degree.

the problem comes when I serialize in json and load back. the custom attributes are in , but shapes like the IText raise an exception such as :

fabric.js:22199 Uncaught TypeError: Cannot read property 'split' of undefined

Looking into the dumped json I can see the .text attribute is not exported. So My fear is that overriding the toObject I lose some of the custom attributes of the default object.

Of course I can redefine it in my toObject function with all the missing trims, but I though that

fabric.util.object.extend

would have done that for me.

Can someone point me on what I'm doing wrong ? thanks. L.

p.s here is a snippet of the outcome json:

{"type":"i-    text","originX":"left","originY":"top","left":29,"top":677,"width":107,"height":22.6,"fill":"rgba(255,255,255,1)","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"uuid":"04af6ab4-4eb1-432b-f46a-93b11a92292d","rt_attributes":[["fontFamily","text"],["fontSize","int"],["fill","color"],["opacity","float"],["top","int"],["left","int"]],"styles":{}},

as you can see there's no text field., but uuid and rt_attributes are in.


回答1:


Finally found the proper way:

fabric.Object.prototype.toObject = (function (toObject) {
    return function (propertiesToInclude) {
        propertiesToInclude = (propertiesToInclude || []).concat(
          ['uuid','rt_attributes']
        );
        return toObject.apply(this, [propertiesToInclude]);
    };
})(fabric.Object.prototype.toObject);


来源:https://stackoverflow.com/questions/41286547/fabric-js-extending-toobject-with-custom-properties-loses-default-ones

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