Fabric.js子类化fabric.Group - 错误:"无法读取属性' async'未定义"从JSON加载时

时间:2014-06-24 10:55:03

标签: javascript json canvas fabricjs

有以下问题:

尝试继承fabric.Group:

var CustomGroup = fabric.util.createClass(fabric.Group, {
    type : 'customGroup',

    initialize : function(objects, options) {
        options || ( options = { });

        this.callSuper('initialize', objects, options);
        this.set('customAttribute', options.customAttribute || 'undefinedCustomAttribute');
    },

    toObject : function() {
        return fabric.util.object.extend(this.callSuper('toObject'), {
            customAttribute : this.get('customAttribute')
        });
    },

    _render : function(ctx) {
        this.callSuper('_render', ctx);
    }
});

测试用例:

我创建了一个红色矩形并将其添加到自定义组:

function drawTestRect() {
    // create a rectangle object
    var rect = new fabric.Rect({
        left : 100,
        top : 100,
        fill : 'red',
        width : 20,
        height : 20
    });

    var cgroup = new CustomGroup([rect], {
        top : 50,
        left : 50,
        customAttribute : 'Hello World'
    });

    canvas.add(cgroup);

};

问题: 我想获得画布的JSON,之后我想从JSON加载画布。

  

drawTestRect()

     

var savedCanvas = canvas.toJSON();

     

canvas.clear();

     

canvas.loadFromJSON(savedCanvas);

一切正常(绘制了Rect / Group; JSON有效),但是当我从JSON加载时,我在控制台中收到以下错误:

  

TypeError:无法读取属性' async'未定义的

我已尝试过的内容:

  • 我添加了" CustomGroup.async = false; "。但没有帮助

1 个答案:

答案 0 :(得分:12)

引发错误“无法读取未定义的属性'async'”,因为找不到“klass” - https://github.com/kangax/fabric.js/blob/master/src/util/misc.js#L214-215

您必须将自定义对象分配给fabric对象 - 否则canvas.loadFromJSON()不起作用。

var fabric.CustomGroup = fabric.util.createClass(fabric.Group, {
    type : 'customGroup',

    initialize : function(objects, options) {
        options || ( options = { });

        this.callSuper('initialize', objects, options);
        this.set('customAttribute', options.customAttribute || 'undefinedCustomAttribute');
    },

    toObject : function() {
        return fabric.util.object.extend(this.callSuper('toObject'), {
            customAttribute : this.get('customAttribute')
        });
    },

    _render : function(ctx) {
        this.callSuper('_render', ctx);
    }
});

此外,您必须声明fromObject方法 - loadFromJSON需要它。 在这种情况下,您的对象是加载同步的。

fabric.CustomGroup.fromObject = function (object, callback) {
    var _enlivenedObjects;
    fabric.util.enlivenObjects(object.objects, function (enlivenedObjects) {
        delete object.objects;
        _enlivenedObjects = enlivenedObjects;
    });
    return new fabric.CustomGroup(_enlivenedObjects, object);
};

如果您的自定义对象已加载异步,则必须执行以下操作:

fabric.CustomGroup.fromObject = function (object, callback) {
    fabric.util.enlivenObjects(object.objects, function (enlivenedObjects) {
        delete object.objects;
        callback && callback(new fabric.CustomGroup(enlivenedObjects, object));
    });
};

fabric.CustomGroup.async = true;

我做了一个小jsfiddle测试用例:http://jsfiddle.net/Kienz/qPLY6/