How to clone an object in the FabricJS?

2

In FabricJs, using the canvas.getActiveObject() function, you can return the value of the currently active object.

I would like to know if there is any way to clone this object and add it to the canvas, with the same proportions and modifications.

Example:

var canvas = new fabric.Canvas('canvas', {preserveObjectStacking: true});


document.querySelector('#adicionar-objeto').addEventListener('click', function () {

    fabric.Image.fromURL(url, function (image) {

        image.scale(0.3);

        image.opacity = .7;

        canvas.add(image);

        canvas.centerObject(image);
   });

})

document.querySelector('#clonar-objeto').addEventListener('click', function () {
      var obj = canvas.getActiveObject();

      // Quero clonar esse objeto aqui e adicioná-lo ao canvas
})
    
asked by anonymous 25.08.2018 / 20:25

2 answers

3

There is a method for cloning objects.

document.querySelector('#clonar-objeto').addEventListener('click', function () {
    var obj = fabric.util.object.clone(canvas.getActiveObject());
    obj.set("top", 0);
    obj.set("left", 0);
    canvas.add(obj);
});
    
25.08.2018 / 22:49
-2

To clone an object (or more object) in JavaScript you can use the Object.assign () .

    const origem = {
       a: 1,
       b: 2
    };

    const destino = Object.assign({}, origem);

    console.log(origem, destino);
    
25.08.2018 / 22:52