Skip to content

How to set additional properties in all fabric.Objects

Howon Song edited this page Sep 7, 2020 · 2 revisions

How to set additional properties in all fabric.Objects

You usually add an element to canvas like this:

const text = new fabric.Text(an.text, {
  left: 100,
  top: 100,
});
canvas.add(text);

Sometimes, you want to add additional properties (e.g. id) to an element.

const text = new fabric.Text(an.text, {
  left: 100,
  top: 100,
});
text.id = 'text-1234'
canvas.add(text);

But when you serialize/deserialize, you will notice that this additional property does not persist. That's because Fabric implements a custom toJSON function that relies on its own toObject function, for which you must specify which properties must be persisted. Therefore, to persist the additional property (e.g. id) that you added above, you must override toObject function of the specific class (e.g. Text) or the top-level Object class.

const originalToObject = fabric.Object.prototype.toObject;
const myAdditional = ['id'];
fabric.Object.prototype.toObject = function (additionalProperties) {
    return originalToObject.call(this, myAdditional.concat(additionalProperties));
}