Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to add data to a FabricJS object and use them when exporting the canvas

This is the 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 get the 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'd like to add an object inside this image, just like this:

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

And be able to get it from the return of _canvasJSON().

like image 234
fabioxd20 Avatar asked Dec 30 '25 09:12

fabioxd20


1 Answers

If you need to add/get any custom key&value pair to any fabricJS object, you can do that as you do with any other key&value pair:

image.set('width', 100);
image.get('width');

image.set('customKey', 'Custom value added here');
image.get('customKey');

image.set({
  borderColor: 'black',
  values: 123
  transparentCorners: false,
});
image.get('values');

If you need to export a fabricJS canvas, use this:

const customKeys = ['customKey', 'values'];
canvas.toJSON(customKeys);

toJSON() accepts an array as a parameter. That array MUST include any custom key that you've attached to any object. It also needs any key that it's not part of the 'default' keys from an object(e.g: 'evented', hoverCursor', 'scaleX', etc.)

use canvas.loadFromJSON(json) to load the exported json.

More details about toJSON in the documentation.

like image 101
Cooble Avatar answered Jan 01 '26 01:01

Cooble