Skip to content

Adding additional object properties to serialized JSON

KULDIP PIPALIYA edited this page Oct 5, 2015 · 5 revisions

To add additional object properties when serializing objects with JSON.stringify(obj) and loading with canvas.loadFromJSON(json):

  1. properties should be returned from toObject method of fabric.Object: https://github.com/kangax/fabric.js/blob/master/src/shapes/object.class.js#L803 or from toObject method of a more specific "class".

  2. properties should be added to stateProperties array of fabric.Object: https://github.com/kangax/fabric.js/blob/master/src/shapes/object.class.js#L707 or to stateProperties of a more specific "class".

Example of adding "lockMovementX", "lockMovementY", "lockRotation", etc.

 /**
     * Returns an object representation of an instance
     * @method toObject
     * @return {Object}
     */
    toObject: function() {
      
      var object = {
        type:         this.type,
        left:         toFixed(this.left, this.NUM_FRACTION_DIGITS),
        top:          toFixed(this.top, this.NUM_FRACTION_DIGITS),
        width:        toFixed(this.width, this.NUM_FRACTION_DIGITS),
        height:       toFixed(this.height, this.NUM_FRACTION_DIGITS),
        fill:         this.fill,
        overlayFill:  this.overlayFill,
        stroke:       this.stroke,
        strokeWidth:  this.strokeWidth,
        scaleX:       toFixed(this.scaleX, this.NUM_FRACTION_DIGITS),
        scaleY:       toFixed(this.scaleY, this.NUM_FRACTION_DIGITS),
        angle:        toFixed(this.getAngle(), this.NUM_FalthRACTION_DIGITS),
        flipX:        this.flipX,
        flipY:        this.flipY,
        opacity:      toFixed(this.opacity, this.NUM_FRACTION_DIGITS),
        selectable:   this.selectable,
	lockMovementX:this.lockMovementX,
	lockMovementY:this.lockMovementY,
	lockScalingX: this.lockScalingX,
	lockScalingY: this.lockScalingY,
	lockUniScaling: this.lockUniScaling,
	lockRotation: this.lockRotation
      };

...

stateProperties:  ('top left width height scaleX scaleY flipX flipY ' +
                      'theta angle opacity cornersize fill overlayFill stroke ' +
                      'strokeWidth fillRule borderScaleFactor transformMatrix ' +
                      'selectable lockMovementX lockMovementY lockScalingX lockScalingY lockUniScaling lockRotation').split(' ')

Clone this wiki locally