isuru
isuru

Reputation: 3565

How to keep property value of object?

This question belongs to fabricJS and canvas. I have define a property named background and initially it set as a false. I need to change object's property state as a true when user add a object to a canvas.

I have tried using background = true; but it change property value in whole canvas. How I do this for particular object when it add to the canvas.

Upvotes: 0

Views: 81

Answers (1)

Freeman Lambda
Freeman Lambda

Reputation: 3675

If you want objects to have a background property, you need to equip the fabric.js Object type with a background property, by adding that to the prototype.

fabric.Object.prototype.background = false;

Later when you add an object, you can select your target object and assing

myObject.background = true

If you need to alter the object that is being added, you can listen to the object:added global listener on the canvas, like this:

myCanvas.on( 'object:added', function( e ) {
        var object = e.target;
        object.background = true;
} );

If you use object serialization somewhere in your code, you might need to modify the fabricjs-provided object serialization method to include your newly added background property.

fabric.Object.prototype.toObject = ( function ( toObject ) {
    return function () {
        return fabric.util.object.extend( toObject.call( this ), {
            background: this.background
        } );
    };
} )( fabric.Object.prototype.toObject );

Upvotes: 2

Related Questions