Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FabricJs - How do I Add properties to each object

Tags:

fabricjs

I need to introduce few additional properties to existing object properties set.

like:

  1. ID
  2. Geo Location
  3. etc

Whenever I draw a shape, I need to add additional properties to the shape and need to get from toDataLessJSON()

like image 814
user3816670 Avatar asked Jul 08 '14 13:07

user3816670


2 Answers

As of version 1.7.0 levon's code stopped working. All you need to do is to fix as follows:

// Save additional attributes in Serialization
fabric.Object.prototype.toObject = (function (toObject) {
    return function (properties) {
        return fabric.util.object.extend(toObject.call(this, properties), {
            textID: this.textID
        });
    };
})(fabric.Object.prototype.toObject);

You have to receive properties argument and pass it on to toObject.

like image 176
temuri Avatar answered Nov 20 '22 10:11

temuri


Here's a code for adding custom properties and saving them in JSON serialization for any object on canvas. (I used standard javascript object properties, but it works for me)

canvas.myImages = {};
fabric.Image.fromURL('SOME-IMAGE-URL.jpg', function(img) {
      canvas.myImages.push(img);
      var i = canvas.myImages.length-1;

      canvas.myImages[i].ID = 1;  // add your custom attributes
      canvas.myImages[i].GeoLocation = [40, 40];

      canvas.add(canvas.myImages[i]);
      canvas.renderAll();
});

And you then include the custom attribute in object serialization.

// Save additional attributes in Serialization
fabric.Object.prototype.toObject = (function (toObject) {
    return function () {
        return fabric.util.object.extend(toObject.call(this), {
            textID: this.textID
        });
    };
})(fabric.Object.prototype.toObject);

// Test Serialization
var json = JSON.stringify(canvas.toDatalessJSON());
console.log(json);

canvas.clear();

// and load everything from the same json
canvas.loadFromDatalessJSON(json, function() {
    // making sure to render canvas at the end
    canvas.renderAll();
}
like image 33
levon Avatar answered Nov 20 '22 10:11

levon