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.
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!
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