在 Fabricjs 的背景文本中添加填充和边框半径

Adding padding and border radius in background text in Fabricjs

是否有机会在 Fabric JS 背景文本上添加填充和边框半径我想让它看起来像号召性用语按钮

JS

canvas = new fabric.Canvas('mainCanvas',
    backgroundColor: 'green'
)


text = new fabric.IText('hello world', 
    left: 200
    top: 100
    backgroundColor: "pink",
)
canvas.add(text)

HTML

<canvas id="mainCanvas" style="border:1px solid #aaa" width="600" height="300"></canvas> 

JSFIDDLE

我通过简单地对元素进行分组解决了这个问题,在 fabric.Rect 中我添加了 rx: 5ry: 5 作为边界半径。

代码全了JSFIDDLE

var canvas = window._canvas = new fabric.Canvas('c1');




var bg = new fabric.Rect({
  fill: '#32b775',
  scaleY: 0.5,
  originX: 'center',
  originY: 'center',
  rx: 5, 
  ry: 5,
  width: 90,
  height:80
});

var text = new fabric.Text('Done', {
  fontSize: 18,
  originX: 'center',
  originY: 'center',
  fill: '#FFF'
});

var group = new fabric.Group([ bg, text ], {
  left: 50,
  top: 100
});

canvas.add(group);
canvas {
    border: 1px solid #999;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>

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

如果有人正在寻找 Textbox

的解决方案

这是您可以尝试的另一种解决方案:https://github.com/fabricjs/fabric.js/issues/3731

var TextboxWithPadding = fabric.util.createClass(fabric.Textbox, {
  _renderBackground: function(ctx) {
    if (!this.backgroundColor) {
      return;
    }
    var dim = this._getNonTransformedDimensions();
    ctx.fillStyle = this.backgroundColor;

    ctx.fillRect(
      -dim.x / 2 - this.padding,
      -dim.y / 2 - this.padding,
      dim.x + this.padding * 2,
      dim.y + this.padding * 2
    );
    // if there is background color no other shadows
    // should be casted
    this._removeShadow(ctx);
  }
});

扩展基础 class 并覆盖 _renderBackground 函数。

非常简单,很适合我!