Deserialize a JSON object in Fabric.js

▼魔方 西西 提交于 2019-11-30 22:49:30

问题


I am developping a collaborative whiteboard using fabricjs. When a user creates a new fabric object , I serialize it and send it to all other users.

var rect = new fabric.Rect();
canvas.add(rect);  
socket.emit("newObject", JSON.stringify(rect)); // sends the object to other users

When those users receive the serialized object, it should be deserialized and added to their canvas. What is the best way to do this? I was not able to find a function that deserializes a single object, only the whole canvas (loadFromJSON), so I implemented an unelegant solution:

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();
}

Any suggestions for a better way to do it?


回答1:


You can use fabric.util.enlivenObjects to deserialize json objects. After all objects are deserialized you have to add them:

objects.forEach(function(o) {
  canvas.add(o);
});

Here is the complete example - replace obj1, obj2 with your objects. Example is also available on 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();
});


来源:https://stackoverflow.com/questions/19361971/deserialize-a-json-object-in-fabric-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!