Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize a JSON object in Fabric.js

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?

like image 750
stropitek Avatar asked Oct 14 '13 13:10

stropitek


1 Answers

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();
});
like image 142
Kienz Avatar answered Sep 28 '22 05:09

Kienz