How to clone an object in Fabricjs?

Asked

Viewed 51 times

2

In Fabricjs, through the function canvas.getActiveObject() it is possible to 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 current 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
})

2 answers

3


There is a method to clone 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);
});

-2

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

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

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

    console.log(origem, destino);
  • It is not to clone the Javascript object, but the canvas object. The answer does not answer the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.