【问题标题】:Define labelled line using Fabric JS使用 Fabric JS 定义标记线
【发布时间】:2020-12-16 23:46:18
【问题描述】:

我正在尝试创建一个名为标记线的新形状。如下图所示。我决定使用 Fabric JS 并扩展 fabric.line 类。

新类扩展 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);
  }
});

调用

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

问题

如何在行之间或仅在行的左侧或右侧实现标签?或在行旁边 看起来,我没有正确扩展它,我在这里缺少什么?我也看不到没有标签的行。

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

【问题讨论】:

    标签: javascript css fabricjs


    【解决方案1】:
    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

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      相关资源
      最近更新 更多