Fabric.js-如何创建没有换行符的文本框?

问题描述

我在Fabric.js文档中搜索maxLinesNowrapsplitByWhitespace属性,但它们并不存在。您知道在fabric.TextBox禁用文本换行的有效解决方案吗?

我的代码

const text = new window.fabric.TextBox('expected single line',{
  fontFamily: 'Nunito Sans',fontWeight: 400,fontSize: 15,originX: 'center',originY: 'center',});

const border = new window.fabric.Rect({
  rx: 10,ry: 10,fill: '#999999',height: text.height + 10,width: text.width + 100,});

const group = new window.fabric.Group([border,text],{
  originX: 'left',originY: 'top',hasRotatingPoint: false,height: 42,width: 200,top: 167,left: 50,});
canvas.add(group);

实际结果演示

multiline textbox

如您所见,每个空格都有换行符,但是我想使用一行加空格的文本。有趣的是,如果我用下划线_替换空格,则会得到一行文本。

演示:

one-line textbox

解决方法

我不知道在Textbox中禁用换行。
但是要获得单行文字,您可以

  • 设置Textbox的宽度
  • 或使用Text代替Textview(请参阅此codepen
,

最初在这里找到:https://stackoverflow.com/a/41335051/1815624

此sorta通过检查fixedWidthfixedHeight的加值,然后在更改文本后检查与新宽度比较的值来实现您想要的...

这并不是真正的解决方案,但可以帮助您解决问题...

// ADD YOUR CODE HERE
var canvas = new fabric.Canvas('c');
var t1 = new fabric.Textbox('MyText',{
    width: 150,top: 5,left: 5,fontSize: 16,textAlign: 'center',fixedWidth: 150,fixedHeight: 20,});

canvas.on('text:changed',function(opt) {

    
  var t1 = opt.target;
  if (t1.width > t1.fixedWidth) {
    t1.fontSize *= t1.fixedWidth / (t1.width + 1);
    t1.width = t1.fixedWidth;
  }
  if(t1.height > t1.fixedHeight){
  
    t1.fontSize *= t1.fixedHeight / (t1.height + 1);
    t1.height = t1.fixedHeight;
  }
  canvas.renderAll(); 
                 
});

canvas.add(t1);
canvas {
    border: 1px solid #999;
}
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="600" height="600"></canvas>