【问题标题】:Adding padding and border radius in background text in Fabricjs在 Fabricjs 的背景文本中添加填充和边框半径
【发布时间】:2016-06-23 15:42:54
【问题描述】:

是否有机会在 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

【问题讨论】:

    标签: javascript coffeescript fabricjs


    【解决方案1】:

    我通过简单地对元素进行分组来解决问题,并在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>

    【讨论】:

      【解决方案2】:

      如果有人正在寻找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);
        }
      });
      

      扩展基类并覆盖_renderBackground函数。

      非常简单,适合我!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-15
        • 2021-06-11
        • 2012-03-13
        相关资源
        最近更新 更多