Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js stage.getActiveObject().clone() vs. fabric.util.object.clone(stage.getActiveObject())

I'm using Fabric.js and I'm trying to implement a copy function for images and text element. I found two solutions for on how to copy objects:

Method 1

stage.getActiveObject().clone();

Method 2

fabric.util.object.clone(stage.getActiveObject());

When using the first method, the cloning won't occur, when using the second method the cloning does occur. To be more specific, for the first method I used the following code:

var obj = stage.getActiveObject();
if (!obj) return;

var clone = obj.clone();
clone.set({
    top: clone.get('top') + 30
});
stage.add(clone);
stage.renderAll(); 

When running this code on an active object it keeps telling that clone is undefined. Although both methods would do the same thing there must a good reason for using either method 1 or 2.

Could anyone explain the difference between those 2?

Another thing I noticed is that when using the 2nd method, fabric.util.object.clone(stage.getActiveObject()); the cloned object gets the same ID as the original object. Although cloning makes a clone of the original I wouldn't make sense to me that they share the same ID. In other words, how can I clone an object and give it a unique ID?

like image 882
Jerome Bohg Avatar asked Feb 12 '14 11:02

Jerome Bohg


1 Answers

Ok, so I figured out a solution for my issue. It works for me so maybe it can help others. This is my final code that does what I'm after.:

var object = fabric.util.object.clone(stage.getActiveObject());
stage.discardActiveObject();

object.title = object.title + '_copy';
object.id = (object.id * 2);
object.set("top", object.top+20);
object.set("left", object.left+20);

stage.add(object);
stage.renderAll();

I need a unique ID per object for my application so I'm multiplying the original ID by 2. Still, if someone has a better solution or can give me more info on why Method 1 from my post above didnt work feel free to leave a note.

like image 141
Jerome Bohg Avatar answered Oct 10 '22 12:10

Jerome Bohg