[英]JSON.stringify() Unable to save Object ID Fabric JS
I am setting an id attribute for a Group Object 我正在为组对象设置id属性
group.id = "N";
canvas.add(group);
canvas.renderAll();
Now, When I am serializing the canvas using 现在,当我使用
JSON.stringify(canvas);
And then reloading the Canvas using the Json Saved 然后使用保存的Json重新加载Canvas
canvas.loadFromJSON(canvas_json , canvas.renderAll.bind(canvas) , function(o , obj)
{
if(obj.type == 'group')
{
console.log('OBJ ID -'+obj.id);
}
});
I get OBJ ID -undefined 我得到OBJ ID-未定义
I checked a few solutions some involve subclassing, but since I am pretty deep in the application it won't be the best solution for me. 我检查了一些涉及子类化的解决方案,但是由于我对应用程序非常了解,因此它并不是我的最佳解决方案。
I tried something like 我尝试了类似的东西
fabric.Object.prototype.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
id: this.id
});
};
But it was in vain. 但这是徒劳的。 Do I have to loop through each object in the canvas and manually add the id attribute to the json?
我是否必须遍历画布中的每个对象,然后将id属性手动添加到json? I am sure there must be a better solution than that.
我敢肯定,有比这更好的解决方案。
Any help in this regards would be very helpful. 在这方面的任何帮助将非常有帮助。
Check out the function toObject(propertiesToInclude)
on the canvas
object ( fabric.js doc ). 在
canvas
对象( fabric.js doc )上toObject(propertiesToInclude)
出函数toObject(propertiesToInclude)
)。 You should use this method to "export" the canvas
before using JSON.stringify
to serializing. 在使用
JSON.stringify
进行序列化之前,应该使用此方法“导出” canvas
。 The function allows you to provide a list of additional properties that should be included in the serialization. 该函数允许您提供序列化中应包括的其他属性列表。
When deserializing you just use the reviver
function to set the needed property from o
to obj
( obj.id = o.id
). 反序列化时,只需使用
reviver
函数将所需的属性从o
为obj
( obj.id = o.id
)。
Putting it all together: 放在一起:
var canvas, group; // your canvas and group objects
group.id = 'N';
canvas.add(group)
canvas.renderAll();
var canvasJson = JSON.stringify(canvas.toObject(['id']));
canvas.loadFromJSON(canvasJson, canvas.renderAll.bind(canvas), function(jsonObject, fabricObject) {
// jsonObject is the object as represented in the canvasJson
// fabricObject is the object that fabric created from this jsonObject
if (fabricObject.type === 'group') {
fabricObject.id = jsonObject.id
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.