Add data to an object/image in Fabricjs

Asked

Viewed 32 times

0

I need to add data to an object in Fabricjs and search for them again when exporting the canvas.

Function I use to add an object:

function _addImageObject(imageURL) {
  fabric.util.loadImage(imageURL, function (imageLoaded) {

    var image = new fabric.Image(imageLoaded);

    image.set({
      borderColor: 'black',
      cornerColor: 'black',
      cornerStrokeColor: 'white',
      cornerSize: 11,
      transparentCorners: false,
    });

    canvas.add(image);
    canvas.centerObject(image);
    canvas.setActiveObject(image);
    canvas.renderAll();
  });
}

Function used to fetch objects:

 function _canvasJSON() {
      try {
        let canvasCopy = _copyCanvas(canvas);

        let canvasJSON = {
          canvasImage: JSON.stringify(canvasCopy),
          svg: canvas.toSVG()
        };
        return canvasJSON;
      } catch (e) {
        canvas.renderAll();
      }
    }

function _copyCanvas() {
     let canvasString = JSON.stringify(canvas);
     return JSON.parse(canvasString);
}

I wanted to add an object inside this image, example:

image.set('key', { values: 123});

And be able to get it back on _canvasJSON();

1 answer

1



To add new information, you need to create an object, use obj.set() and render the canvas. Example:

var obj = canvas.getActiveObject(); obj.set('foo','bar'); canvas.renderAll();

Once this is done, the new information will already be inside your object, but it is not yet available in JSON.

To do this, just specify on JSON.stringify.Example:

var json = JSON.stringify(canvas.toJSON(['foo']));


To search for the entered information, just search for it inside an object. Example: var obj = canvas.getActiveObject(); console.log(obj.foo);

Browser other questions tagged

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