Amogh Raghuram
Amogh Raghuram

Reputation: 13

fabric.js - Adding custom properties to a shape

I am trying to add some custom properties for a rectangle.

I have tried setting the toObject property as per the fabric.js documentation.

let rect = new fabric.Rect();

    rect.toObject = ((toObject) => {
        return () => {
            return fabric.util.object.extend(toObject.call(this), {
                name: 'some name'
            });
        };
    })(rect.toObject);

    this.canvas.add(rect);

When I click on save of the canvas

this.canvas.toJSON();

I am getting a ERROR TypeError: this.callSuper is not a function.

Upvotes: 1

Views: 1498

Answers (1)

Durga
Durga

Reputation: 15614

Because this value is not proper inside arrow function. Either change it to normal function, or pass rect object instead this.

const canvas = new fabric.Canvas('c')
const rect = new fabric.Rect();

rect.toObject = (function(toObject) {
  return function(propertiesToInclude) {
    return fabric.util.object.extend(toObject.call(this, propertiesToInclude), {
      name: 'some name'
    });
  };
})(rect.toObject);

canvas.add(rect);
console.log(canvas.toJSON())
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script>
<canvas id='c'></canvas>

Upvotes: 1

Related Questions