使用canvas.toJSON();
无法导出自定义画布属性。
我必须使用画布原型。但是我不知道如何构建原型结构。
现有(允许)数据:
var clipFath = this.clipPath, data = {
version: fabric.version,
objects: this._toObjects (methodName, propertiesToInclude),
};
我需要这种方式:
var clipFath = this.clipPath, data = {
version: fabric.version,
objects: this._toObjects (methodName, propertiesToInclude),
custom_settings_json: this.custom_settings /* <-- */
};
原始来源line 7698:
在以下示例中,我可以将自定义设置添加到结构对象。我需要一个类似的画布结构。 Source
fabric.Object.prototype.toObject = (function (toObject) {
return function (propertiesToInclude) {
propertiesToInclude = (propertiesToInclude || []).concat(
['custom_attr_1','custom_attr_2'] /* <- */
);
return toObject.apply(this, [propertiesToInclude]);
};
})(fabric.Object.prototype.toObject);
我尝试将其设置为画布,如下所示
var canvas = new fabric.Canvas('canvas');
var custom = {
"data1": 1,
"data2": 2
}
canvas.custom_settings_json = custom;
var json_data = canvas.toJSON();
console.log(json_data);
// console log:
{
"version":"2.4.1",
"objects":[{.....}],
"custom_settings_json": {
"data1": 1,
"data2": 2
}
}
但是我在custom_settings_json
输出中没有toJSON
的情况下得到了这个结果。
// console log:
{
"version":"2.4.1",
"objects":[{.....}]
}
答案 0 :(得分:1)
您需要从_toObjectMethod
扩展fabric.StaticCanvas
方法。
我举了一个例子jsfiddle。
打开控制台,您将看到toJSON
方法中的json,其中包含自定义参数data1,data2,data3。
//rewrite core
fabric.StaticCanvas.prototype._toObjectMethod = (function(toObjectMethod) {
return function(propertiesToInclude) {
return fabric.util.object.extend(toObjectMethod.call(this, "toDatalessObject", propertiesToInclude), {
data1: this.data1,
data2: this.data2,
data3: this.data3,
});
};
})(fabric.StaticCanvas.prototype._toObjectMethod);
//end
var myCanvas = new fabric.Canvas('my-canvas');
myCanvas.data1 = 1;
myCanvas.data2 = 2;
myCanvas.data3 = 4;
console.log(myCanvas.toJSON(['test']));
<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.6/fabric.min.js'></script>
<canvas id="my-canvas" width="550" height="550"> </canvas>
答案 1 :(得分:1)
您可以扩展画布的toJSON
。基本上,您需要在将画布数据获取为json之后添加属性,之后再添加自定义属性即可。
演示
fabric.Canvas.prototype.toJSON = (function(toJSON) {
return function(propertiesToInclude) {
return fabric.util.object.extend(toJSON.call(this,propertiesToInclude), {
custom_settings_json: this.custom_settings_json
});
}
})(fabric.Canvas.prototype.toJSON);
var canvas = new fabric.Canvas('c', {
"custom_settings_json": {
"data1": 1,
"data2": 2
}
});
canvas.add(new fabric.Circle({
left: 10,
top: 10,
radius: 50
}))
console.log(canvas.toJSON())
canvas{
border:2px solid;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c"></canvas>