Fabric js 使用自定义属性扩展 toObject,丢失默认属性

hdd*_*hdd 6 javascript json fabricjs

在发布这个之前,我一直在这里和许多其他地方一样查找,但我可以让它完全工作。

我所需要的只是能够在所有形状中保存一些自定义属性。属性是:uuid 和 rt_attributes。

因此,按照手册,我添加了以下代码:

 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);
Run Code Online (Sandbox Code Playgroud)

在一定程度上确实可以正常工作。

当我在 json 中序列化并加载回来时,问题就出现了。自定义属性在 中,但像 IText 这样的形状会引发异常,例如:

fabric.js:22199 Uncaught TypeError: Cannot read property 'split' of undefined
Run Code Online (Sandbox Code Playgroud)

查看转储的 json 我可以看到 .text 属性没有导出。所以我担心覆盖 toObject 会丢失默认对象的一些自定义属性。

当然,我可以在我的 toObject 函数中使用所有缺少的修剪重新定义它,但我认为

fabric.util.object.extend
Run Code Online (Sandbox Code Playgroud)

会为我做的。

有人可以指出我做错了什么吗?谢谢。L。

ps 这里是结果 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":{}},
Run Code Online (Sandbox Code Playgroud)

如您所见,没有文本字段。但 uuid 和 rt_attributes 在。

hdd*_*hdd 6

终于找到了正确的方法:

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