wrahim
wrahim

Reputation: 1168

How to restore/reuse json serialized objects in fabricjs?

I am trying to create a collaborative whiteboard with socket.io and fabric.js.

When a user draws something I send the path to other users as a JSON format:

canvas.on('path:created', function(e) {
  canvas.remove(fabric.Path.fromObject(JSON.stringify(e.path)));
  socket.emit('add path', e.path.toJSON());
});

How can I recreate this object on the canvas here?

socket.on('add path', function(path) {
  canvas.add(path); // doesn't work
});

Upvotes: 3

Views: 2226

Answers (2)

Leonardo Viada
Leonardo Viada

Reputation: 413

For those calling this function in a TypeScript project... In my case setting namespace to empty string ('') and explicitly typing the callback argument made the function work smoothly.

fabric.util.enlivenObjects(
        action.payload.objects,
        (enlivedObjects: fabric.Object[]) => {
          canvas.add(...enlivedObjects);
          canvas.renderAll();
        },
'');

Upvotes: 0

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

try to use fabric.util.enlinvenObjects

The purpouse of that function is to switch from object form to istance.

socket.on('add path', function(path) {
  fabric.util.enlivenObjects([path], function(objects) {
    objects.forEach(function(o) {
      canvas.add(o);
    });
  });
});

Upvotes: 3

Related Questions