Search code examples
javascriptcssfabricjs

Define labelled line using Fabric JS


I am trying to create a new shape called labelled line. something like below picture. I decided to use Fabric JS and Extending the fabric.line class.

New class extends Line

var LabelledLine = fabric.util.createClass(fabric.Line, {

  type: 'lline',
  // initialize can be of type function(options) or function(property, options), like for text.
  // no other signatures allowed.
  initialize: function(options) {
    options || (options = { });

    this.callSuper('initialize', options);
    this.set('label', options.label || '');
  },

  toObject: function() {
    return fabric.util.object.extend(this.callSuper('toObject'), {
      label: this.get('label')
    });
  },

  _render: function(ctx) {
    this.callSuper('_render', ctx);

    //ctx.font = '20px Helvetica';
    //ctx.fillStyle = '#333';
    // ctx.fillText(this.label, -this.width/2, -this.height/2 + 20);
  }
});

Invocation

var l = LabelledLine({
    coords: [250, 125, 250, 175], label:'Label'
  })
  canvas.add(l);

Problem

How do achieve label exactly between the line or just left or right of line ? or next to line looks like, I am not extending it properly, anything I am missing here? I am not able to see the line without label also.

Error
caught TypeError: Cannot read property 'apply' of undefined
    at klass (fabric.js:2238)
    at Image.background.onload

enter image description here


Solution

  • var Edge = fabric.util.createClass(fabric.Line, {
    
        type: 'edge',
        // initialize can be of type function(options) or function(property, options), like for text.
        // no other signatures allowed.
        initialize: function(points, options){
          options = options || {};
          this.points = points || [];
    
          this.callSuper('initialize',points, options);
          this.set('label', options.label || '');
        },
    
        toObject: function() {
          return fabric.util.object.extend(this.callSuper('toObject'), {
            label: this.get('label')
          });
        },
    
        _render: function(ctx) {
          this.callSuper('_render', ctx);
    
          ctx.font = '9px Helvetica';
          ctx.fillStyle = '#333';
          ctx.fillText(this.label,  -this.width/2, -this.height/2 + 20);
          // ctx.fillText(this.label, -this.width/2, -this.height/2 + 20);
        }
      });
    
    
      var lr = new Edge([ 250, 125, 500, 175 ], {
        fill: 'green',
        stroke: 'green',
        strokeWidth: 1,
        selectable: true,
        evented: true,
        hasBorders:false,
        cornerStyle:'circle',
        lockScalingX: true,
        lockScalingY:true,
        label: '1'
      });
      canvas.add(lr);
    
    };
    

    https://codepen.io/ajayramesh/pen/NWNpaRW