我正在使用fabricjs开发协作白板.当用户创建新的结构对象时,我将其序列化并将其发送给所有其他用户.
var rect = new fabric.Rect();
canvas.add(rect);
socket.emit("newObject", JSON.stringify(rect)); // sends the object to other users
当这些用户收到序列化对象时,应将其反序列化并添加到其画布中.做这个的最好方式是什么?我无法找到一个反序列化单个对象的函数,只有整个画布(loadFromJSON),所以我实现了一个不优雅的解决方案:
function drawRoomObjects(roomObjects){
var canvasString = "{\"objects\":[";
for(var roomObjectKey in roomObjects){
canvasString += roomObjects[roomObjectKey];
}
canvasString += "], \"background\":\"\"}";
var tmpCanvas = new fabric.Canvas();
tmpCanvas.loadFromJSON(canvasString);
for(var k in tmpCanvas.getObjects()) {
canvas.add(tmpCanvas._objects[k]);
}
canvas.renderAll();
}
有什么建议可以做更好的方法吗?
解决方法:
您可以使用fabric.util.enlivenObjects反序列化json对象.反序列化所有对象后,您必须添加它们:
objects.forEach(function(o) {
canvas.add(o);
});
这是完整的示例 – 将obj1,obj2替换为您的对象.
示例也可在jsfiddle上获得.
fabric.util.enlivenObjects([obj1, obj2], function(objects) {
var origRenderOnAddRemove = canvas.renderOnAddRemove;
canvas.renderOnAddRemove = false;
objects.forEach(function(o) {
canvas.add(o);
});
canvas.renderOnAddRemove = origRenderOnAddRemove;
canvas.renderAll();
});