【问题标题】:Fabric.js - how to create TextBox without line breaks?Fabric.js - 如何创建没有换行符的文本框?
【发布时间】:2020-12-20 19:29:02
【问题描述】:

我在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,
  originX: 'center',
  originY: 'center',
});

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);

实际效果演示:

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

演示:

【问题讨论】:

    标签: javascript textbox fabricjs


    【解决方案1】:

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

    • 要么设置Textbox 宽度
    • 或使用Text 代替Textview(参见codepen

    【讨论】:

      【解决方案2】:

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

      通过检查 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>

      【讨论】:

      • 在代码 sn-p 中,我没有看到文本周围有边框。
      猜你喜欢
      • 2016-10-17
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多