为ittext添加自定义属性

fabric.js add custom property to IText

本文关键字:自定义属性 添加 ittext      更新时间:2023-09-26

我想添加一个自定义属性到fabricjs。在文本中,我使用了与我的fabricjs相同的脚本。文本类:

fabric.CustomIText = fabric.util.createClass(fabric.IText, {
        type        : 'custom-itext',
        initialize  : function(element, options) {
            this.callSuper('initialize', element, options);
            options && this.set('textID', options.textID);
        },
        toObject: function() {
            return fabric.util.object.extend(this.callSuper('toObject'), {textID: this.textID});
        }
    });    
    fabric.CustomIText.fromObject = function(object) {
        return new fabric.CustomIText(object.text, object);
    };
    fabric.CustomIText.async = false;  

当我创建新的自定义文本时,没有问题。

 var text    = new fabric.CustomIText('NewText', { left: 0, top: 0 , fill: color, fillColor:color, textID: "SommeID"});
    canvas.add(text);

但是当我想从JSON中加载我的新customittext时,我有一个javascript错误:

Uncaught TypeError: Cannot read property 'async' of undefined

谢谢

下面的代码为画布上的任何对象保存序列化中的附加属性。这可能会解决你的问题,它为我工作

// Save additional attributes in Serialization
fabric.Object.prototype.toObject = (function (toObject) {
    return function () {
        return fabric.util.object.extend(toObject.call(this), {
            textID: this.textID
        });
    };
})(fabric.Object.prototype.toObject);

我让它与异步初始化工作:

fabric.TextAsset = fabric.util.createClass(fabric.IText, {
    type: 'textAsset',
    initialize: function(element, options) {
        this.callSuper('initialize', element, options);
        this.set('extraProp', options.extraProp);
    },
    toObject: function() {
        return fabric.util.object.extend(this.callSuper('toObject'), {
            extraProp: this.get('extraProp')
        });
    }
});
fabric.TextAsset.fromObject = function (object, callback) {
    callback(new fabric.TextAsset(object.text, object));
};
fabric.TextAsset.async = true;
}