我遇到了一个在fabric.js中序列化的奇怪问题。
我创建了一个带有几个自定义属性的自定义Group对象。我已经实现了toObject()方法来处理自定义属性。
var customGrpFieldOptions = {
"name":"fabric-custom-grp",
"includeCField1" : true,
"includeCField2" : false,
"includeCField3" : false,
"includeCField4" : true
};
var customGrpObject = new fabric.Group([], customGrpFieldOptions);
customGrpObject.toObject = (function(toObject) {
return function() {
return fabric.util.object.extend(toObject.call(this), {
includeCField1: this.includeCField1,
includeCField2: this.includeCField2,
includeCField3: this.includeCField3,
includeCField4: this.includeCField4
});
};
})(customGrpObject.toObject);
我序列化canvas对象以保存它。序列化的JSON具有自定义属性。
当我将对象重新加载到画布时,我可以看到该对象具有自定义属性。 但是,当我再次序列化画布时,属性不会被包含在内。
我创建了一个JSFiddle来演示这个问题。 https://jsfiddle.net/bbcstar/9x48kk7f/
这里出了什么问题?我错过了什么吗?
非常感谢任何帮助!
答案 0 :(得分:3)
Andrea Bogazzi(@asturur)建议我应该传递一系列自定义字段,这些字段需要包含在序列化中。这有助于解决此特定问题。
然而,令我惊讶的是,为什么序列化在原始状态下工作正常而不需要传递数组。
var json = JSON.stringify( canvas.toJSON() );
loadFromJSON之前的序列化画布
json : {"objects":[{"type":"group","originX":"left","originY":"top","left":0,"top":0,"width":0,"height":0,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"objects":[],"includeCField1":true,"includeCField2":false,"includeCField3":false,"includeCField4":true}],"background":""}
使用loadFromJSON将序列化状态加载到画布后,当我们再次序列化对象时,我们需要明确提及需要包含的自定义字段。
var json2 = JSON.stringify( canvas.toJSON(["includeCField1", "includeCField2","includeCField3","includeCField4"]) );
loadFromJSON之后的序列化画布:
{"objects":[{"type":"group","originX":"left","originY":"top","left":0,"top":0,"width":0,"height":0,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,**"includeCField1":true,"includeCField2":false,"includeCField3":false,"includeCField4":true**,"objects":[]}],"background":""}
答案 1 :(得分:0)
我解决了这个问题。
canvas.loadFromJSON(Json, function ()
{
debugger;
canvas.renderAll();
console.log(JSON.stringify(canvas));
var json = canvas.toJSON(['selectable', 'name', 'ownType', 'ddlValue', 'lockScalingX']);
console.log(JSON.stringify(json))
});