【问题标题】:Draw border on Fabric Textbox when it's not selected未选中时在 Fabric Textbox 上绘制边框
【发布时间】:2018-07-14 04:00:03
【问题描述】:

In this jsfiddle 我有一个 Fabric(1.x 版)文本框,当它被选中时有一个红色边框,当文本可编辑时有一个蓝色边框。我需要的是未选择 TextBox 时的边框。如何实现?

HTML

<canvas id="c" width="300" height="300"></canvas>

Javascript

var canvas = new fabric.Canvas('c');

var text = new fabric.Textbox("Some Text", {
  left: 50,
  top: 50,
  width: 100,
  fontSize: 12,
  fontFamily: 'Arial',
  backgroundColor: 'yellow',
  borderColor: 'red',
  editingBorderColor: 'blue',
  padding: 2
});

canvas.add(text);

【问题讨论】:

    标签: fabricjs


    【解决方案1】:

    您可以覆盖文本框对象的渲染方法。并为文本对象绘制边框。

    演示

    var canvas = new fabric.Canvas('c');
    
    var originalRender = fabric.Textbox.prototype._render;
    fabric.Textbox.prototype._render = function(ctx) {
      originalRender.call(this, ctx);
      //Don't draw border if it is active(selected/ editing mode)
      if (this.active) return;
      if(this.showTextBoxBorder){
        var w = this.width,
          h = this.height,
          x = -this.width / 2,
          y = -this.height / 2;
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.lineTo(x + w, y);
        ctx.lineTo(x + w, y + h);
        ctx.lineTo(x, y + h);
        ctx.lineTo(x, y);
        ctx.closePath();
        var stroke = ctx.strokeStyle;
        ctx.strokeStyle = this.textboxBorderColor;
        ctx.stroke();
        ctx.strokeStyle = stroke;
      }
    }
    fabric.Textbox.prototype.cacheProperties = fabric.Textbox.prototype.cacheProperties.concat('active');
    
    var text = new fabric.Textbox("Some Text\n some more text", {
      left: 50,
      top: 50,
      width: 100,
      fontSize: 12,
      fontFamily: 'Arial',
      backgroundColor: 'yellow',
      borderColor: 'red',
      editingBorderColor: 'blue',
      padding: 2,
      showTextBoxBorder: true,
      textboxBorderColor: 'green'
    });
    canvas.add(text);
    canvas{
     border : 2px solid #000;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.7/fabric.js"></script>
    <canvas id="c" width="300" height="300"></canvas>

    【讨论】:

    • 我发现你的回答有问题。如果您首先单击文本框将其选中,然后调用一个函数取消全选,则边框会消失。请参阅here。首先单击文本框,然后单击按钮。
    • @ps0604 as deactivateAll() 不会触发事件,因此会失败。使用deactivateAllWithDispatch()。这里更新了fiddle
    • 请看here,我还是有问题。如果您选择了两个对象,然后通过单击按钮取消选择,第一个对象将失去边框。
    • @ps0604 这里更新了fiddle,将活动添加到缓存属性。我认为它不会再次失败;)
    • this.active 条件在较新的 fabricjs 版本中不起作用
    【解决方案2】:

    你不能只添加这样的东西吗?

    border-style: solid;
    border-color: coral;
    

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 1970-01-01
      • 2011-11-13
      • 2013-06-17
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多