Search code examples
clonefabricjs

fabricjs cloned object affect old(default) object


I am trying to get shadow Image of Text object without affecting the output of fabric.

Code

var clonedText = jQuery.extend({}, obj);
clonedText.fill = "rgba(50,50,50,0.5)";
imageURL = clonedText.toDataURL({format:'png'});

Result

Default:enter image description here AfterRun:enter image description here

How can it be fixed? I mean how can I copy object so that cant affect default image?

UPDATE:

I also tried this and this.

canvas._objects.forEach(function(obj, index){
 var clonedText = fabric.util.object.clone(obj);
    clonedText.fill = "rgba(50,50,50,0.5)";
    imageURL = clonedText.toDataURL({format:'png'});
});

This has same result.


Solution

  • So you should not really clone instances like you would clone javascript objects. Fabric objects can have references to canvas elements, image elements, deep structures, and every clone logic works on its own.

    on fabricjs docs is specified that fabric.util.object.extende/clone does not clones fabricJS objects:

    http://fabricjs.com/docs/fabric.util.object.html

    Also in the docs is specified the clone method:

    enter image description here

    So you have to run

    myText.clone(function(cloned) {
      // do something with cloned....
    });
    

    If you are in need of a full syncronous process, and you are not using patterns or image sources for text you can also do:

    var objectForm = myText.toObject();
    var clonedText = new fabric.Text(objectForm.text, objectForm);