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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With