admin管理员组

文章数量:1287811

Is there any chance to add padding and border radius on Fabric JS background text i want to look like call to action button

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

Is there any chance to add padding and border radius on Fabric JS background text i want to look like call to action button

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

Share Improve this question edited May 9, 2018 at 3:18 Cœur 38.7k26 gold badges203 silver badges277 bronze badges asked Mar 9, 2016 at 10:15 Edin PuzicEdin Puzic 1,0482 gold badges23 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

I solved the problem by simply grouping the elements and in fabric.Rect I added rx: 5 and ry: 5 for border radius.

There is all the code 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./kangax/fabric.js/master/dist/fabric.js"></script>

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

If anyone is looking for a solution with Textbox,

Here's another solution you can try: https://github./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);
  }
});

Extend the base class and overwrite the _renderBackground function.

Very simple and works well for me!

本文标签: javascriptAdding padding and border radius in background text in FabricjsStack Overflow