小编典典

从Fabric.js继承Fabric.Group的子类-错误:从JSON加载时“无法读取未定义的属性'async'”

json

有以下问题:

试图继承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:无法读取未定义的属性“异步”

我尝试过的

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

阅读 388

收藏
2020-07-27

共1个答案

小编典典

出现错误“无法读取未定义的属性’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/

2020-07-27