1

我正在使用库 FabricJS 在画布上覆盖文本。我需要向包含属性 textBackgroundColor 的文本元素添加填充(最好是左右)。

这是我迄今为止尝试过的:

let textObject = new fabric.Text('Black & White',{
    fontFamily: this.theme.font,
    fontSize: this.theme.size,
    textBaseline: 'bottom',
    textBackgroundColor: '#000000',
    left: 0,
    top: 0,
    width: 100,
    height: 40,
    padding: 20,
    fill: 'white',
});

填充不像我预期的那样工作。我曾尝试使用 backgroundColor 属性,但这会将背景添加到整个组块,而不仅仅是文本。

我可以添加一个不间断的空间来实现相同的效果,但这似乎不是一个可靠的解决方案,我希望 Fabric JS 允许这个开箱即用。任何想法如何实现这一目标?

所需的解决方案(右边的版本,我想要的是额外的填充):

在此处输入图像描述

4

2 回答 2

4

对于两种微妙不同的情况,我给你 2 个答案。

案例 1 - 在单行文本的边界框周围填充。代码遵循 CSS 方法,其中边距位于框外,如红线所示,内边距位于框内,如金色背景所示。在左侧图像中,黑色文本背景是您从内置的“textBackgroundColor”中获得的。黄色区域显示当前应用的填充。右侧的图像显示了协调填充颜色时的额外好处,您还可以减少背景的不透明度,同时保持文本完全不透明。

顺便说一句,与控制边框相关的文本填充的内置“填充”属性,但背景颜色填充不覆盖创建的空白。换句话说,它的操作类似于 CSS 边距而不是 CSS 填充。

因此有必要忽略这个填充属性,而是引入一个彩色矩形来提供所需的背景颜色,将其与文本元素分组并相应地定位。

案例 1 示例

下面的示例片段。

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

// function to do the drawing. Could easily be accomodated into a class (excluding the canvas reset!) 
function reset(pos)
{

canvas.clear();

// Create the text node - note the position is (0, 0)
var text = new fabric.Text(pos.text, {
    fontFamily: 'Arial',
    left: 0,
    top: 0,
    fill: "#ffffff",
    stroke: "",
    textBackgroundColor: '#000000'
});

// create the outer 'margin' rect, note the position is negatively offset for padding & margin 
// and the width is sized from the dimensions of the text node plus 2 x (padding + margin).
var rectMargin =   new fabric.Rect({
    left: -1 *  (pos.padding.left + pos.margin.left), 
    top: -1 * (pos.padding.top + pos.margin.top),
    width: text.width + ((pos.padding.left + pos.padding.right) + (pos.margin.left + pos.margin.right)), 
    height: text.height + ((pos.padding.top + pos.padding.bottom) + (pos.margin.top + pos.margin.bottom)),
    strokeWidth: pos.border,
    stroke: 'red',
    fill: 'transparent'
})

// create the inner 'padding' rect, note the position is offset for padding only
// and the width is sized from the dimensions of the text node plus 2 x padding.
var rectPadding =   new fabric.Rect({
    width: text.width + (pos.padding.left + pos.padding.right), 
    height: text.height + (pos.padding.top + pos.padding.bottom),
    left: -1 *  pos.padding.left, top: -1 * pos.padding.top,
    fill: 'gold'
})

// create group and add shapes to group, rect first so it is below text.
// note that as the group is oversized, we position it at pos - padding. 
var group = new fabric.Group([ rectMargin, rectPadding, text ], {
  left: pos.x - (pos.padding.left - pos.margin.left),
  top: pos.y - (pos.padding.top - pos.margin.top),
  angle: pos.angle,
});

canvas.add(group);
}

// function to grab values from user inputs
function go()
{
var m = $('#margin').val().split(',');
var p = $('#padding').val().split(',');
for (var i = 0 ; i < 4; i = i + 1)
{
  p[i] = parseInt(p[i], 10); // ensure we have numbers and not strings !
  m[i] = parseInt(m[i], 10);
}


// Object holding position and content info
var pos = {x: 50, y : 10, text: 'Text with padding\nand another line', 
  padding: {top:p[0], right:p[1], bottom: p[2], left: p[3]}, margin: {top:m[0], right:m[1], bottom: m[2], left: m[3]}, border: 1, angle: 10};

reset(pos);
}

// click handler for go button
$('#go').on('click', function(e){
  go();
  
})

// call go once to show on load
go();
div
{
  background-color: silver;
  width: 600px;
  height: 300px;
}
.ipt
{
margin-right: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.1/fabric.min.js"></script>
<p>
<span class='ipt'> Margin: <input id='margin' value = '12,10,12,10' /></span> 
<span class='ipt'> Padding: <input id='padding' value = '0,5,0,5' /></span> 
<span class='ipt'><button id='go' />Go</button></span> 
<div>
  <canvas id="c" width="600" height="300"></canvas>
</div>

案例 2:填充单个文本行而不是整个边界框

在这种情况下,您可以看到填充背景如何跟踪每行文本而不是应用于文本的外部边界框的差异。解决方案更复杂,包括创建一个虚拟文本节点,然后提供行拆分和大小信息。然后我们循环遍历行数据,将单个文本行和填充矩形输出到一个组中,这意味着我们可以将文本作为单个对象定位和处理,如应用角度所示。

案例 2 的示例。

var textIn = 'Text goat\nMillenium jam\nplumb\nBlack & White'

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

// function to do the drawing. Could easily be accomodated into a class (excluding the canvas reset!) 
function reset(pos)
{

 canvas.clear();
  
// Create the text measuring node - not added to the canvas !
var textMeasure = new fabric.IText(pos.text, {
    fontFamily: 'Arial',
    left: 0,
    top: 0,
    fill: "#ffffff",
    stroke: "",
    textBackgroundColor: '#000000'
});

// loop round the lines in the text creating a margin/pad scenario for each line
var theText, text, textHeight, rectPadding, rectMargin, top = 0, shapes = [];
for (var i = 0; i < textMeasure._textLines.length; i = i + 1){
  theText = textMeasure._textLines[i].join('');
  textHeight = Math.floor(textMeasure.lineHeight * textMeasure.fontSize) //textMeasure.getHeightOfLine(i)

  // Make the text node for line i
  text = new fabric.IText(theText, {
      fontFamily: 'Arial',
      left: 0,
      top: top,
      fill: "#ffffff",
      stroke: ""
  });


  // create the outer 'margin' rect, note the position is negatively offset for padding & margin 
  // and the width is sized from the dimensions of the text node plus 2 x (padding + margin).
  rectMargin =   new fabric.Rect({
      left: -1 *  (pos.padding.left + pos.margin.left), 
      top: top - (pos.padding.top + pos.margin.top),
      width: text.width + ((pos.padding.left + pos.padding.right) + (pos.margin.left + pos.margin.right)), 
      height: textHeight + ((pos.padding.top + pos.padding.bottom) + (pos.margin.top + pos.margin.bottom)),
      fill: 'transparent'
  })
  shapes.push(rectMargin);

  // create the inner 'padding' rect, note the position is offset for padding only
  // and the width is sized from the dimensions of the text node plus 2 x padding.
  rectPadding =   new fabric.Rect({
      width: text.width + (pos.padding.left + pos.padding.right), 
      height: textHeight + (pos.padding.top + pos.padding.bottom),
      left: -1 *  pos.padding.left, 
      top: top - pos.padding.top,
      fill: '#000000ff'
  })
  shapes.push(rectPadding);
  shapes.push(text);

  // move the insert point down by the height of the line
  var gap = 0; // text.lineHeight - textHeight;
  top = top - 1 + textHeight + pos.padding.top + pos.margin.top + pos.padding.bottom + pos.margin.bottom;
}

// At this point we have a list of shapes to output in the shapes[] array.
// Create group and add the shapes to group.
// note that group is positioned so that the topleft of the first text line is where
// it would fall if it were a standard text node. 
var group = new fabric.Group(shapes, {
  left: pos.x - (pos.padding.left - pos.margin.left),
  top: pos.y - (pos.padding.top - pos.margin.top),
  angle: pos.angle,
});

canvas.add(group);

}

// function to grab values from user inputs
function go()
{
var m = $('#margin').val().split(',');
var p = $('#padding').val().split(',');
for (var i = 0 ; i < 4; i = i + 1)
{
  p[i] = parseInt(p[i], 10); // ensure we have numbers and not strings !
  m[i] = parseInt(m[i], 10);
}


// Object holding position and content info
var pos = {x: 70, y : 10, text: textIn, 
  padding: {top:p[0], right:p[1], bottom: p[2], left: p[3]}, margin: {top:m[0], right:m[1], bottom: m[2], left: m[3]}, border: 1, angle: 10};

reset(pos);
}

// click handler for go button
$('#go').on('click', function(e){
  go();
  
})

// call go once to show on load
go();
div
{
  background-color: silver;
  width: 600px;
  height: 100px;
}
.ipt
{
margin-right: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.1/fabric.min.js"></script>
<p>
<span class='ipt'> Margin: <input id='margin' value = '0,0,0,0' /></span> 
<span class='ipt'> Padding: <input id='padding' value = '5,15,5,15' /></span> 
<span class='ipt'><button id='go' />Go</button></span> 
<div>
  <canvas id="c" width="600" height="300"></canvas>
</div>

于 2018-10-22T07:49:46.747 回答
0

如果有人正在寻找解决方案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函数。

非常简单,对我来说效果很好!

于 2020-11-19T01:49:28.650 回答