Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning objects in Fabric.js

I am cloning a selected object on a canvas in Fabric.js using a simple function.

function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone); 
}

That works absolutely fine. Now if I work with the object and the clone is not required anymore and I select and delete it, both objects, the clone and the original object are deleted. The delete function is:

function deleteObj() {
  var obj = canvas.getActiveObject();
  canvas.fxRemove(obj);
}

The objects are the same. Is there are way to clone objects and make the clone independent of the of the original? I tried this:

function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.initialize();
  $.extend(clone, obj);
  fabric.util.object.extend(clone, obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone); 
}

It works, however the objects are the same again and if I only use initialize I am ending up with an object that has now properties set.

like image 424
py66WJAm Avatar asked Feb 10 '14 08:02

py66WJAm


1 Answers

This worked very well for me, and the cloned object is totally unlinked from the original:

var object = canvas.getActiveObject();

object.clone(function(clone) {
    canvas.add(clone.set({
        left: object.left + 10, 
        top: object.top + 10
    }));
});

And you can do it to clone all selected objects:

var activeObjects = canvas.getActiveObjects();

if (activeObjects) {
    activeObjects.forEach(function(object) {

        object.clone(function(clone) {
            canvas.add(clone.set({
                left: object.left + 10, 
                top: object.top + 10
            }));
        })

    });
}

I hope it can help you!

like image 159
Tiago Silva Pereira Avatar answered Sep 18 '22 14:09

Tiago Silva Pereira