【问题标题】:fabric-js textBakgroundColor not covering whole text when changing object property更改对象属性时,fabric-js textBakgroundColor 不覆盖整个文本
【发布时间】:2018-07-07 04:36:44
【问题描述】:

我正在使用fabric-js 在画布上创建模板。但面临有线问题。

我在画布上添加了一个 Textbox 对象,当我尝试更改 TextboxfontFamilyfontWeight 时,有时 textBackgroundColor 不会覆盖整个文本.

我创建了一个jsfiddle 来展示这个问题。

重现步骤:

  • 选择文本框对象,将fontFamily从Merriweather改为Lato
  • 然后将 fontWeight 从 normal 更改为 bold

注意:这是针对特定字体(例如 Merriweather)而不是针对 全部,有时它也有效,但不是每次都有效。

【问题讨论】:

  • 我猜这已经在新版本中修复了,check
  • @Durga 它不固定,我使用的是最新版本2.0.0-rc.4
  • 检查我发布的小提琴
  • 我查过了,还是不行,换个fontFamily就可以看到问题了。

标签: javascript css canvas fabricjs


【解决方案1】:

当字体未正确加载时会发生这种情况。 fabricJs 请求粗体字体,即未准备好,甚至常规字体也未准备好,并使用后备进行渲染。 当字体准备好时,字体测量已经完成,并且是错误的。

您必须使用字体加载器正确加载字体。 查一下fontFaceObeserver,真的好用。

在下面的 sn-p 中,我只使用了一个非常 hacky 的 setTimeout 和 2 段来强制浏览器提前加载字体。

var canvas = new fabric.Canvas('canvas');
setTimeout(function() {
text = new fabric.Textbox("Click here twice to edit", {
  width: 300,
  fontSize: 25,
  fontFamily: 'Merriweather',
  textAlign: 'center',
  textBackgroundColor : '#000',
  fill: '#ffc107',
});
canvas.add(text);

window.toggleBoldText = function() {
  var obj = canvas.getActiveObject();
  if(obj){
    if (obj.get('fontWeight') == 'normal'){
      obj.set('fontWeight', 'bold');
    }else{
      obj.set('fontWeight', 'normal');
    }
  	canvas.renderAll();
  }else{
    alert("select text object to add font weight");
  }
}

window.toggleFontFamily = function() {
  var obj = canvas.getActiveObject();
  if(obj){
   if (obj.get('fontFamily') == 'Merriweather'){
      obj.set('fontFamily', 'Lato');
    }else{
      obj.set('fontFamily', 'Merriweather');
    }
    canvas.renderAll();
  }else{
    alert("select text object to add font family");
  }  
}

}, 3000);
@import url(//fonts.googleapis.com/css?family=Merriweather%7CLato);

.canvas-container {
  border: 1px dotted #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
<button onclick="toggleFontFamily()">toggle font family</button>
<button onclick="toggleBoldText()">toggle bold</button>
<span style="font-family: Merriweather; font-weight: bold;">Merri bold</span><span style="font-family: Merriweather; font-weight: normal;">Merri normal</span>
<canvas width="500" height="300" id="canvas"></canvas>

【讨论】:

    【解决方案2】:

    有同样的问题,但我创建了带有选项的选择元素,用户可以在其中选择他需要的字体。在我不在选择选项上使用字体样式之前,但经过几个小时的谷歌搜索后,我意识到可以将该字体添加到列表中,并且字体将被下载。

    在那之后,fabricjs 工作得很好

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 2011-11-19
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多