首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fabricjs固定TextBox

Fabricjs固定TextBox
EN

Stack Overflow用户
提问于 2017-08-16 18:50:16
回答 3查看 5.4K关注 0票数 5

如何固定textBox的大小,以防止其在键入时溢出(固定的宽度和高度)?

代码语言:javascript
复制
var canvas = window._canvas = new fabric.Canvas('c');

var text = new fabric.Textbox('MyText', {
    width: 300,
    height: 300,
    top: 5,
    left: 5,
    hasControls: false,
    fontSize: 30,
    fixedWidth: 300,
    fixedFontSize: 30
});
canvas.add(text);

http://jsfiddle.net/643qazk0/2/

EN

回答 3

Stack Overflow用户

发布于 2017-11-13 21:19:02

您可以重写insertChars方法并检查文本溢出。

请参阅下面的代码片段。

代码语言:javascript
复制
// Create canvas
const canvas = new fabric.Canvas(document.querySelector('canvas'));

// Define `LimitedTextbox` class which extends `Textbox`
const LimitedTextbox = fabric.util.createClass(fabric.Textbox, {

  // Override `insertChars` method
  insertChars: function(chars) {

    if (this.maxWidth) {
      const textWidthUnderCursor = this._getLineWidth(this.ctx, this.get2DCursorLocation().lineIndex);
      if (textWidthUnderCursor + this.ctx.measureText(chars).width > this.maxWidth) {
        chars = '\n' + chars;
      }
    }

    if (this.maxLines) {
      const newLinesLength = this._wrapText(this.ctx, this.text + chars).length;
      if (newLinesLength > this.maxLines) {
        return;
      }
    }

    // Call parent class method
    this.callSuper('insertChars', chars);
  }

});

// Create limited text box with max width 300px and max 2 lines
canvas.add(
  new LimitedTextbox('text', {
    top: 10,
    left: 10,
    width: 300,
    maxWidth: 300,
    maxLines: 2
  })
);

canvas.renderAll();
代码语言:javascript
复制
.canvas-container {
  border: 1px solid gray;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>

<canvas width="600" height="300"></canvas>

使用Fabric 1.7.20进行测试

票数 3
EN

Stack Overflow用户

发布于 2019-12-16 21:31:15

对于fabric js版本2+中的固定文本框,我们需要覆盖onInput函数,如下所示

代码语言:javascript
复制
onInput: function(e) {
    if(this.width > this.maxWidth) {
        return;
    }

    if((this._textLines.length) > this.maxLines) {
        return;
    }

    // Call parent class method
    this.callSuper('onInput', e);
}

注意: maxWidth -限制宽度,maxLines -限制文本框中的高度/行数

票数 1
EN

Stack Overflow用户

发布于 2021-03-30 19:10:34

该解决方案仅提供了字符的表示的here块。在引擎盖下,隐藏的文本区继续接受字符。

因此,如果允许并单击退格键-所有在maxLines之后编写的不可见文本都将弹出。

Solution:使用以下代码将隐藏文本区域与文本同步:

代码语言:javascript
复制
 if (this._textLines.length > this.maxLines && e.inputType !== 'deleteContentBackward') {
    this.hiddenTextarea.value = this.text;
    return;
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45711558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档