Deserialize a JSON object in Fabric.js

stropitek picture stropitek · Oct 14, 2013 · Viewed 7.7k times · Source

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?

Answer

Kienz picture Kienz · Oct 14, 2013

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