简体   繁体   中英

fabric.js add custom property to IText

I want to add a custom property to fabricjs.IText, i used a same script i used with my fabricjs.Text class:

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;  

When I create my new custom-itext there is no problem.

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

But whene I want to load my new CustomItext from a JSON i have a javascrip error:

Uncaught TypeError: Cannot read property 'async' of undefined

Thank you

Here's a code saving additional attributes in serialization for any object on canvas. This might solve your problem, it worked for me

// 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);

I got it to work with async initialization:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM