Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric js extending toObject with custom properties, loses default ones

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.

like image 334
hdd Avatar asked Dec 22 '16 15:12

hdd


1 Answers

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);
like image 70
hdd Avatar answered Nov 15 '22 01:11

hdd