FabricJs - How do I Add properties to each object

大憨熊 提交于 2019-12-04 12:51:17

问题


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()


回答1:


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.




回答2:


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();
}


来源:https://stackoverflow.com/questions/24633740/fabricjs-how-do-i-add-properties-to-each-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!